Thursday, December 20, 2007

Silverlight and Javascript Interaction

Silverlight is a relatively new client side technology released by Microsoft, but already people are finding the need to communicate between their Silverlight applications and Javascript. This tutorial will go through all the code required to call Javascript functions from Silverlight and vice-versa.
All the Silverlight code and examples were created using the 1.1 Alpha Refresh. Before you can use the example application below, you'll need to download the runtime (if you haven't already). If you're new to Silverlight, check out our introductory tutorial for information on what to download and how to get started.

Before we jump into code, let's look at an example of some communication between Silverlight and Javascript. The application on the left was created using Silverlight, the one on the right was made using HTML and CSS. When one of the buttons on the left is clicked, a message will be displayed on the right indicating that. The same thing happens when a button on the right is clicked.

So let's see how something like this is done. We'll start with the hard one - calling a Javascript function from Silverlight. There's no direct way (that I know of) to simply call a Javascript function directly from the Silverlight code behind. What we have to do is create events and attach to them from the Javascript code. This isn't a lot of work, but being able to call them directly would be a nice feature to have. So let's look at some
C# code behind that creates the events.


using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Browser;namespace SilverlightJavascript{ [Scriptable] public partial class Page : Canvas { [Scriptable] public event EventHandler ButtonAClicked; [Scriptable] public event EventHandler ButtonBClicked; [Scriptable] public event EventHandler ButtonCClicked; public void Page_Loaded(object o, EventArgs e) { // Required to initialize variables InitializeComponent(); WebApplication.Current.RegisterScriptableObject( "SilverlightApp", this); } }}

Since my Silverlight application has three buttons, I created three events - one for each button. They're created and used exactly like they are in an ordinary C# Windows application. One difference I'm sure you noticed is the [Scriptable] attribute above the definition of the class and each event. This lets Silverlight know that this class and these events should be accessible from the Javascript code. The next thing you might have noticed is the RegisterScriptableObject call. With this function we're telling Silverlight to make this class accessible via scripts by the name "SilverlightApp". Now whenever I want to use this object in Javascript, I'll reference it by the name "SilverlightApp". We'll see how this works later. Now that everything is setup, let's look at some C# code to fire our newly created events.

void ButtonA(object sender, MouseEventArgs e){ if (ButtonAClicked != null) ButtonAClicked(this, e);}void ButtonB(object sender, MouseEventArgs e){ if (ButtonBClicked != null) ButtonBClicked(this, e);}void ButtonC(object sender, MouseEventArgs e){ if (ButtonCClicked != null) ButtonCClicked(this, e);}

In my XAML code I hooked up a MouseLeftButtonUp event to each of my buttons. Now when a button is clicked, one of these functions will be called. As you can see, firing the events is no different than a C# application. You should always make sure to check that an event is not null before firing it - otherwise things tend to crash. An event will be null if nothing has attached to it. That's all the code required on the Silverlight side to call Javascript functions. Now let's look at how to make Javascript listen for these events. The first thing we need to do is attach Javascript functions to each event. We'll do this as soon as the Silverlight application is done loading. So now you're probably wondering, how do we know when the Silverlight is done loading? There's an event we can listen for that is called as soon as it's finished. In order to get this event we need to modify the Javascript that Visual Studio generated as part of the test code. In my solution, the .js file is named TestPage.html.js. It might be different for you depending on how you set it up.

// JScript source code//
contains calls to silverlight.js, example below loads Page.xamlfunction createSilverlight(){ Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById( "SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {onLoad: OnLoaded} }); // Give the keyboard focus to the Silverlight // control by default document.body.onload = function() { var silverlightControl = document.getElementById('SilverlightControl'); if (silverlightControl) silverlightControl.focus(); }}

This should look very similar to what Visual Studio has created for you. The addition we have to make is in the events: {} section. We need to add an event for onLoad. With this addition, we're telling Silverlight to call the Javascript function OnLoaded as soon as it's finished loading. The OnLoaded function is where we're going to be attaching Javascript functions to our Silverlight events. So let's see how that's done.

function OnLoaded(sender, args)
{
sender.Content.SilverlightApp.ButtonAClicked = ButtonAClicked; sender.Content.SilverlightApp.ButtonBClicked = ButtonBClicked; sender.Content.SilverlightApp.ButtonCClicked = ButtonCClicked;}function ButtonAClicked(){ //The Silverlight A button has been clicked
}
function ButtonBClicked(){ //The Silverlight B button has been clicked }function ButtonCClicked(){
//The Silverlight C button has been clicked
}

The OnLoaded event is automatically passed in the Silverlight object and some event arguments. Here's where we use the "SilverlightApp" name we created above. With those assignments, we're telling Silverlight to execute a Javascript function whenever one of those events is fired. So now, whenever the event ButtonAClicked is fired from the Silverlight Application, the Javascript function ButtonAClicked will be executed. That's it for calling Javascript functions from Silverlight. Now let's look at how to call Silverlight functions from Javascript. This process is much easier than calling Javascript from Silverlight. The first thing we need is a C# function we want called.
Let's add one to our Silverlight code behind.

Scriptable]public void HTMLButtonAClicked(){ //The HTML A button has been clicked}

There nothing special about this function except for the [Scriptable] attribute which makes it accessible by our Javascript code. All that's left is to call this function from the Javascript code.


var slApp = document.getElementById('SilverlightControl');slApp.Content.SilverlightApp.HTMLButtonAClicked();

As you can see, this is much easier than the other way around. The first thing we need to do is get the Silverlight object. You're probably wondering where the "SilverlightControl" id came from which is passed into getElementById. This is set back in the .js file that Visual Studio created for you. All that's left to do is access the class we named "SilverlightApp" and call the HTMLButtonAClicked function. Once that's done, the function we wrote in the C# code behind will be executed. I hoped you enjoyed this tutorial on Silverlight and Javascript interaction. Post a comment if you have any questions.



No comments: