Click here to Skip to main content
15,881,715 members
Articles / Web Development / HTML

Calling Silverlight Method from JavaScript and JavaScript Function from Silverlight

Rate me:
Please Sign up or sign in to vote.
4.89/5 (13 votes)
1 Dec 2011CPOL2 min read 74.9K   2.3K   22   11
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

C#
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

C#
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

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

MainPage.xaml.cs

C#
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.

JavaScript
<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

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.

HTML
 <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.

HTML
<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.

JavaScript
<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)


Written By
Team Leader Reputed IT Company
India India
Having 9+ years of experience in Microsoft.Net Technology.
Experience in developing applications on Microsoft .NET Platform ( Asp.Net, WPF, Silverlight, Windows Phone 7/8).
Experience and knowledge of software design methodologies (Agile), object oriented design, and software design patterns (MVVM).
Experience in Developing android mobile application using Xamarin (mono for android) framework.

http://hirenkhirsaria.blogspot.com/

Comments and Discussions

 
QuestionApplication is going in not responding state Pin
Deepak Ingale7-Apr-15 4:57
Deepak Ingale7-Apr-15 4:57 
AnswerRe: Application is going in not responding state Pin
Hiren Khirsaria12-Apr-15 23:49
professionalHiren Khirsaria12-Apr-15 23:49 
QuestionThis application not working on Chrome Pin
SrinvasV8-Dec-14 23:43
SrinvasV8-Dec-14 23:43 
AnswerRe: This application not working on Chrome Pin
Hiren Khirsaria12-Apr-15 23:52
professionalHiren Khirsaria12-Apr-15 23:52 
GeneralThanks Hiren!!!!!!! Pin
Ravin Singh D27-Oct-13 8:05
Ravin Singh D27-Oct-13 8:05 
i have search arount 4 hours in net for the good article. this one only help for me for my prject. thanks a lot.
GeneralMy vote of 5 Pin
vinayakJJ3-Apr-13 0:07
vinayakJJ3-Apr-13 0:07 
GeneralMy vote of 3 Pin
Morteza Azizi1-Apr-13 19:49
professionalMorteza Azizi1-Apr-13 19:49 
GeneralMy vote of 4 Pin
hrohani6-Nov-12 20:29
hrohani6-Nov-12 20:29 
GeneralMy vote of 5 Pin
Martin Lottering4-Oct-12 9:06
Martin Lottering4-Oct-12 9:06 
Questionvery usefull Pin
mohamad yousef5-Dec-11 20:03
mohamad yousef5-Dec-11 20:03 
GeneralMy vote of 4 Pin
Justin Liu CN4-Dec-11 14:13
Justin Liu CN4-Dec-11 14:13 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.