Click here to Skip to main content
Click here to Skip to main content

Calling Silverlight Method from JavaScript and JavaScript Function from Silverlight

By , 1 Dec 2011
 

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Hiren Khirsaria
Software Developer (Senior)
India India
Member
has 4 + Total Experience in Microsoft.Net Environment.
 
2 + year Excperience in .Net Development with C# and SQL Server 2005/2008.
 
2 + Experience in WPF/Silverlight.
 
Current area of Development in Mono for Android (Xamarin), Silverlight/ WPF and Windows Phone 7 Application.
 
Follow him on : http://hirenkhirsaria.blogspot.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberhiphopper01233 Apr '13 - 0:07 
GeneralMy vote of 3memberMorteza Azizi1 Apr '13 - 19:49 
GeneralMy vote of 4memberhrohani6 Nov '12 - 20:29 
GeneralMy vote of 5memberMartin Lottering4 Oct '12 - 9:06 
Questionvery usefullmembermuhamd yusuf5 Dec '11 - 20:03 
GeneralMy vote of 4memberMember 80291954 Dec '11 - 14:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 2 Dec 2011
Article Copyright 2011 by Hiren Khirsaria
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid