Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling Silverlight Method from JavaScript and JavaScript Function from Silverlight

0.00/5 (No votes)
1 Dec 2011 2  
Communication between JavaScript and Silverlight to calling methods

Introduction

When working with Silverlight, we are working with managed code (C#, VB). Sometimes, we need to callback to HTML page from managed code.

In this article, we walkthrough how to call managed code from JavaScript and call JavaScript function from managed code.

Background

To call JavaScript function from Silverlight, HtmlPage class of System.Windows.Browser namespace is used to allow the user to access and manipulate browser DOM (Document Object Model).

ScriptableMemberAtrribute class indicates that method or property is accessible for JavaScript caller.

To permit user to access method of Silverlight from JavaScript, you have to set [ScriptableMember] attribute to that method.

Using the Code

Let's start step by step including source to demonstrate how to communication between JavaScript and Silverlight.

First we start with Calling JavaScript function from Silverlight

Step 1: First, create one class in a Silverlight project, which describes method to call from JavaScript.

ScriptableClass.cs

public class ScriptableClass
    {
        [ScriptableMember]
        public void ShowAlertPopup(string message)
        {
            MessageBox.Show(message, "Message From JavaScript", MessageBoxButton.OK);
        }
    } 

The above class contains one method with parameter. This method is Scriptable attribute type which provides access to call from JavaScript.

Step 2: In App.xaml.cs file, register Scriptable object.

App.xaml.cs

 private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
            ScriptableClass myScript = new ScriptableClass();
            HtmlPage.RegisterScriptableObject("SL2JS", myScript);
        } 

In application_startup event, we need to register scriptable class using RegisterScriptableObject method.

This HtmlPage.RegisterScriptableObject registers managed object for access by JavaScript code.

Step 3: In User Control, create Button to call JavaScript function.

MainPage.xaml

<Button x:Name="CallingButton"
                    Content="Call JavaScript Method From Silverlight"
                    Height="25"
                    Click="CallingButton_Click"></Button>

MainPage.xaml.cs

 private void CallingButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Invoke
        ("DisplayAlertMessage", "From Silverlight");
        }

By clicking on button, we need to invoke JavaScript function by using System.Windows.Browser.HtmlPage.Window.Invoke method.

This method will call JavaScript "DisplayAlertMessage" method with "From Silverlight" as a passing parameter.

In the next step, write method in HTML page of Web project has XAP file as a Object parameter.

Step 4: Switch to Web project and open HTML page.

Step 5: Create Method in HTML page called from Silverlight.

  <script type="text/javascript">
        
        //From Silverlight
        function DisplayAlertMessage(param1) {
            alert("your are invoke method of javascript \n" + param1);
        }
       
    </script> 

Now we move on to call Silverlight method from HTML page.

Now we move on to Call Silverlight Method from HTML page

Step 1: Create button in HTML page of Web project.

Silverlight2JSViseVersaTestPage.html

<div>
        <div style="width: 250px; background: lightblue; font-weight: bold;height:30px">
            HTML Part
        </div>
        <div>
            <input type="button" value="Calling Silverlight Method From Javascript" 
        onclick="CallSilverlight();" /></div>
    </div>

Step 2: Create object of Silverlight app on load of Object using param.

 <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
            width="100%" height="80%">
            <param name="source" value="ClientBin/Silverlight2JSViseVersa.xap" />
            <param name="onError" value="onSilverlightError" />
            <param name="background" value="white" />
            <param name="minRuntimeVersion" value="4.0.50826.0" />
            <param name="autoUpgrade" value="true" />         
                    <param name="onLoad" value="pluginLoaded" />

            <a href=http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0 
        style="text-decoration: none">
                <img src=http://go.microsoft.com/fwlink/?LinkId=161376 
        alt="Get Microsoft Silverlight"
                    style="border-style: none" />
            </a>
        </object> 

In the above source, we created one parameter, we called one method to create XAP object on load of Silverlight app on Object.

Step 3: Write function "pluginLoaded" to create host application variable.

 <script type="text/javascript">       
        //calling Silverlight method
        var slCtl = null;
        function pluginLoaded(sender, args) {
            slCtl = sender.getHost();
        }
      
    </script> 

This code describes the method that gets Silverlight application object hosted. Using this object, we will call the Silverlight method.

Step 4: Create JavaScript function "CallSilverlight" that calls the Silverlight method.

 <script type="text/javascript">     
        //calling Silverlight method
        var slCtl = null;
        function pluginLoaded(sender, args) {
            slCtl = sender.getHost();
        }
        function CallSilverlight() {
            slCtl.Content.SL2JS.ShowAlertPopup
        ("Testing for Calling Silverlight Method\n From Javascript");
        } 
    </script>

In the above code, CallSilverlight function will invoke Silverlight scriptable member method using hosted object (slCtl).

Conclusion

This is just a simple demo example, you can also use Silverlight property from JavaScript as well as JavaScript member from Silverlight.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here