Combining Silverlight and JavaScript

Silverlight 2 is currently in Beta 1 but even in this early stage it has many amazing features.  One of these features which I was toying around with today was its ability to integrate with its host page's DOM.  What this means is that from Silverlight you are able to call Javascript functions and from JavaScript you can call Silverlight methods.

To demonstrate this feature I created a simple but interesting sample:

image 

 

This webpage which can be found here contains two areas, a JavaScript area and a Silverlight area.  Each has a small square in it.  When you move the square in one area it updates its position in the other.  The beauty of this is how simple it is to make this work.  I will show how I update the squares position from Silverlight and from Javascript:

 

Calling Javascript Functions from Silverlight

This is the simpler of the two.  In Silverlight under the System.Windows.Browser namespace there is an object called HtmlPage.  This object gives you access to the pages DOM.  The code I use to move the square in the JavaScript area is:

 HtmlPage.Window.Invoke("moveBox", newX, newY);

where "moveBox" is the name of a Javascript method I wrote to update the red square's position.

That is all I have to do!

 

Calling Silverlight Methods from Javascript

This is slightly more complicated. First in the Silverlight application I have to mark which class I want to expose to JavaScript as by giving it a Scriptable attribute:

 [ScriptableType]
public partial class Page : UserControl

 

Then I need to register this class so that JavaScript can see it and give it a name for JavaScript to refer to it as:

 HtmlPage.RegisterScriptableObject("silverlightMove", this);

 

Next I need to mark which methods to expose to JavaScript by giving them a  ScriptableMember attribute .   Here I am exposing a method called MoveBox which updates the blue square's position  in the Silverlight application:

 [ScriptableMember]
public void MoveBox(int x, int y)

 

With all this setup done I can now move back to JavaScript and get ready to call the method.  To do this I need to get a reference to the pages Silverlight control:

 silverLightControl = document.getElementById("silverlightControl");

Where "silverlightControl" is the id  applied to my Silverlight application object tag.

 

Once I have a reference to the Silverlight control I am able to invoke the method which I marked as a ScriptableMember using the object name I registered:

 silverLightControl.content.silverlightMove.MoveBox(x, y);

I have now called MoveBox method from my C# code in the Silverlight application using Javascript!

 

The code for this sample can be found at here at MSDN Code Gallery.