Javascript communication to Silverlight 2.0

Tonight working with a proof of concept in regards to the communication between Javascript and Silverlight 2.0 has 2 attributes to help you with the task.

Class attribute [ScriptableType], method attribute [ScriptableMember].

There are a few steps to follow. You need to create a Javascript control and register it with a name to be able to access from Javascript. This is pretty important, make sure you add a unique name per class and mark the class with ScriptableType. Then create the method that you want to have access from JavaScript and mark it with ScriptableMember

Create a User Cointrol in Silverlight.

<UserControl x:Class="SilverlightApplication1.Page"
    Width="400" Height="300">    
    <Canvas Height="200" Width="200">
     <TextBox x:Name="TestText" Text="Something"></TextBox>        
   public partial class Page : UserControl
       public Page()

           HtmlPage.RegisterScriptableObject("SilverlightApp", this);

       public void SendToSilverlight(string sMessage)
           HtmlPage.Window.SetProperty("status", sMessage);

           TestText.Text = sMessage;


On the javascript side.

<head runat="server">
    <title>Test Javascript and Silverlight</title>
    <script type="text/javascript" language="Javascript">
        function sendto() {

            var sText = document.getElementById('Text1');
            var silverlightControl = document.getElementById('Xaml1');

<body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div  style="height:100%;">
        <input id="Text1" type="text" />
        <input id="Button1" type="button" value="button" onclick="sendto();"/>
        <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />            



What about calling JavaScript from Silverlight?

HtmlPage.Window.Invoke("myJavascriptFunction", “text to javascript”);

Related links.

Silverlight 1.1 interaction with javascript

Silverlight interoperability

Download code and solution here

Hope that helps,



1 Comment

Comments have been disabled for this content.