Silverlight Tip of the Day #15 – Communicating between JavaScript & Silverlight

Communicating between Javascript and Silverlight is, fortunately, relatively straight forward. The following sample demonstrates how to make the call both ways.

Calling Silverlight From Java script:

  1. In the constructor of your Silverlight app, make a call to RegisterScriptableObject().This call essentially registers a managed object for scriptable access by JavaScript code. The first parameter is any key name you want to give. This key is referenced in your Javascript code when making the call to Silverlight.
  2. Add the function you want called in your Silverlight code. You must prefix it with the [ScriptableMember] attribute.
  3. In Javascript, you can now call directly into your Silverlight function. This can be done through the document object. From my example below: document.getElementById("silverlightControl").Content.Page.UpdateText("Hello from Javascript!"); where “silverlightControl” is the ID of my Silverlight control.

Calling Javascript From Silverlight:

  1. Javascript can be directly called via the HtmlPage.Window.Invoke() function.

Example for both:

Page.xaml:

 namespace SilverlightApplication
 {
     public partial class Page : UserControl
     {
         public Page()
         {
             InitializeComponent();
  
             HtmlPage.RegisterScriptableObject("Page", this);            
             HtmlPage.Window.Invoke("TalkToJavaScript", "Hello from Silverlight");
         }
  
         [ScriptableMember]
         public void UpdateText(string result)
         {
             myTextbox.Text = result;
         }
     }
 } 

Default.aspx:

 <script type="text/javascript"> 
         function TalkToJavaScript( data)
         {
             alert("Message received from Silverlight: "+data);
             
             var control = document.getElementById("silverlightControl");            
             control.Content.Page.UpdateText("Hello from Javascript!");
         }    
 </script>

Page.xaml:

 <UserControl x:Class="SilverlightApplication7.Page"
     xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
     Width="400" Height="300">
     <Grid x:Name="LayoutRoot" Background="White">
         <TextBlock x:Name="myTextbox">Waiting for call...</TextBlock>
     </Grid>
 </UserControl>

Thank you,

--Mike Snow

 Subscribe in a reader

Comments