Build: Interaction between JavaScript and Silverlight 2

As many questions are usually asked regarding how to interact between Silverlight and JavaScript I am going to spend some lines showing an example so you can keep it as a reference. The sample below works with Silverlight 2 and is based on the Beta 2 that we are dogfooding at Microsoft at the time of this post, I haven’t seen any change on this area on the breaking changes document therefore it seems that the syntax will remain the same.

One of the most interesting namespaces that we have in Silverlight 2 is the System.Windows.Browser, as it allows us to interact with the HTMLPage object that provides access to the current web page that is hosting our plug-in. This class allows us to interact directly with the page, for example we can force navigation:

// We format the destination using a querystring

string Destination = string.Format(@"SecondPage.aspx?MyVar={0}",txtMyContent.Text);

// Sets the new URI with a query string entry

Uri SourceUri = new Uri(HtmlPage.Document.DocumentUri, Destination);

// Navigates to the next page

HtmlPage.Window.Navigate(SourceUri);

As you can see we can interact with the query string as well, indeed, we can read the current one using the following command:

HtmlPage.Document.QueryString;

Not only the navigation is included, also we can post forms to the server using the same class. Beyond this, one of the features that I really like is the ability to call javaScript functions from my managed code; you can use the Invoke method for this:

HtmlPage.Window.Invoke("ExecuteAnimation", txtParams.Text);

To execute the following JavaScript method:
 

function ExecuteAnimation(params)

{
// Do something useful
}

Now, to go to the other direction, we can use get a reference of our XAML component using the name of it and then call a published method:

var ctrl = $get("Xaml1");

ctrl.Content.navObj.SendMessage(“Hello”);

We will need to decorate our method with the ScriptableMember attribute in order to be published to the JavaScript world as follows:

public Page()

{

InitializeComponent();

HtmlPage.RegisterScriptableObject("navObj", this);

}

[ScriptableMember()]

public void SendMessage(string state)

{

  // Do something useful

}

In future entries we are going to dig deeper into how this interaction works and we will explore some best practices.