Export (0) Print
Expand All

Walkthrough: Calling JavaScript from Managed Code

Silverlight

This topic shows how to call JavaScript from managed code in a Web page that includes the Silverlight plug-in. Using managed code in a Silverlight-based application to call client script typically involves the following tasks:

  • Handling the Startup event of the XAML Application object in order to bind client script to the XAML code.

  • Registering the client-script event.

  • Invoking client script from managed class methods.

Note Note:

Silverlight for Windows Phone Silverlight for Windows Phone does not support the HTML Bridge feature.

You need the following components to complete this walkthrough:

  • Silverlight 5.

  • Silverlight Tools for Visual Studio 2010.

  • Microsoft Visual Studio 2010.

All of the Silverlight software is available from the Silverlight download site.

The first step is to create a Silverlight project and a test page.

To create a Silverlight project and test page

  1. Create a new Silverlight Application project named M2JS in Visual Basic or Visual C#. Select the Host the Silverlight application in a new Web site option. For more information, see How to: Create a New Silverlight Project.

  2. Open the M2JSTestPage.html file in Design view.

  3. Add an HTML button to the page.

  4. Set the following properties of the button:

    • id : "btnCallJSMethod"

    • value : "Click to make a managed call to a JavaScript method"

    The following example shows the markup for the button.

    <input type="button" id="btnCallJSMethod"
      value="Click to make a managed call to a JavaScript method" />
    

An App.xaml file is automatically created when you create a Silverlight project. The code-behind file for the App.xaml file (App.xaml.cs for C# and App.xaml.vb for Visual Basic) defines an App class that contains an Application_Startup method. You can write code in this method to bind or establish a connection between your Web page and a managed class.

To bind a client event to XAML code

  1. Open the code-behind class file for the App.xaml file.

  2. At the top of the file, add a using or Imports statement to import the System.Windows.Browser namespace.

  3. Add code to the Application_Startup method that performs the following tasks:

    • Gets a reference to the System.Windows.Browser.HtmlDocument object.

    • Creates a delegate for a method named CallGlobalJSMethod in the current class.

    • Binds the CallGlobalJSMethod method to the click event of the HTML button using the document reference and the delegate.

    The following example shows the completed Application_Startup method.

    
    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
        Me.RootVisual = New Page()
        ' HtmlDocument requires Imports System.Windows.Browser.
        Dim doc As HtmlDocument = HtmlPage.Document
        Dim del As New EventHandler(AddressOf Me.CallGlobalJSMethod)
    
        ' Hook up the simple JavaScript method HTML button.
        doc.GetElementById("btnCallJSMethod").AttachEvent("click", del)
    End Sub
    
    
    
  4. In the App class, add the CallGlobalJSMethod method to perform the following tasks:

    • Get the current date and time and build it into a string that indicates that the date and time was calculated in managed code.

    • Call the HtmlPage.Window.Invoke method to call the client-script function named globalJSMethod, passing it the date-time string.

    The following example shows the completed CallGlobalJSMethod method.

    
    ' Call a global JavaScript method defined on the HTML page.
    Private Sub CallGlobalJSMethod(ByVal sender As Object, ByVal e As EventArgs)
        Dim strMS As String = DateTime.Now.Millisecond.ToString()
        Dim strTime As String = "Time came from managed code" + ControlChars.NewLine _
                  + DateTime.Now.ToLongTimeString() _
                  + " MS = " + strMS
    
        HtmlPage.Window.Invoke("globalJSMethod", strTime)
    End Sub
    
    
    

The next step is to add a client-script function to a Web page that contains the Silverlight plug-in.

To call JavaScript from managed code

  1. Open the M2JSTestPage.html file in Source view.

  2. Just before the closing </head> tag, create a script element.

  3. In the script element, create a CallGlobalJSMethod function that will be called from the managed code. The function will be passed one parameter that contains the data that is passed from the managed-code method.

    The following example shows the globalJSMethod method. The code displays the managed-code data and adds data generated in the client-script function.

    <script type="text/javascript">
    function globalJSMethod(strParamGGS){
        var d = new Date();
        alert(strParamGGS + " \n JavaScript milliseconds: " +
            d.getMilliseconds());
    }
    </script>
    
  4. Build the application.

  5. Right-click the M2JSTestPage.html page and then click View in Browser.

  6. Click the Click to make a managed call to a JavaScript method button.

    A message box displays the time in milliseconds when the managed-code method ran and the time in milliseconds when the client script ran.

The following example shows the App.xaml code-behind and the relevant markup for the HTML test page (M2JSTestPage.html).

Code


' App.xaml.vb
Imports System.Windows.Browser

Partial Public Class App
    Inherits Application

    Public Sub New()
        InitializeComponent()
    End Sub
    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
        Me.RootVisual = New Page()
        ' HtmlDocument requires Imports System.Windows.Browser.
        Dim doc As HtmlDocument = HtmlPage.Document
        Dim del As New EventHandler(AddressOf Me.CallGlobalJSMethod)

        ' Hook up the simple JavaScript method HTML button.
        doc.GetElementById("btnCallJSMethod").AttachEvent("click", del)
    End Sub

    ' Call a global JavaScript method defined on the HTML page.
    Private Sub CallGlobalJSMethod(ByVal sender As Object, ByVal e As EventArgs)
        Dim strMS As String = DateTime.Now.Millisecond.ToString()
        Dim strTime As String = "Time came from managed code" + ControlChars.NewLine _
                  + DateTime.Now.ToLongTimeString() _
                  + " MS = " + strMS

        HtmlPage.Window.Invoke("globalJSMethod", strTime)
    End Sub

End Class


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Silverlight Project Test Page </title>
    <script type="text/javascript">
    function globalJSMethod(strParamGGS){
        var d = new Date();
        alert(strParamGGS + " \n JavaScript milliseconds: " +
        d.getMilliseconds());
    }
    </script>
</head>
<body>
    <div id="silverlightControlHost">
        <input type="button" id="btnCallJSMethod" 
          value="Click to make a managed call to a JavaScript method" />
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
            <param name="source" value="ClientBin/M2JS.xap" />
        </object>
        <iframe id="_sl_historyFrame"
          style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
    </div>
</body>
</html>

Community Additions

ADD
Show:
© 2014 Microsoft