Share via


Exercise 3: Calling JavaScript code from Silverlight

This exercise walks you through the process of calling JavaScript from inside a custom Silverlight application.

Task 1 – Attaching an Event Handler

  1. In this task, you will write code in Silverlight to attach a managed code event handler to an HTML button declared in the HTML DOM. When the button is clicked, the managed code will execute.
  2. If it is still open, close the browser used in Exercise 1
  3. Using Visual Studio 2010, open the starter solution named CallJS from the <Install>\Labs\HTMLBridge\source\begin\Call JavaScript folder. Solution Explorer should look like this:

    Figure 9

    Solution Explorer

  4. From Solution Explorer, open up the file SilverlightApplication1WebPartPage.aspx and scroll all the way to the bottom of the page. Add the following code between the two Call JavaScript comments:

    C#

    <script type="text/javascript"> function helloFromJS(message) { alert("JavaScript says Hello and " + message); } </script>

  5. This code is the JavaScript method that will be called from Silverlight.
  6. From Solution Explorer, open up the Silverlight code behind file by expanding the MainPage.xaml file and double clicking on MainPage.xaml.cs.
  7. Position your cursor on line 12 and add the following using declaration and then hit <Enter>:

    C#

    using System.Windows.Browser;

  8. Referencing this namespace gives us shorthand access to the HTML Bridge classes (such as HtmlDocument, HtmlPage and HtmlElement) we will use throughout the rest of this exercise
  9. Position your cursor on line 25 in the buttonSayHello_Click handler and type the following code:

    C#

    HtmlDocument htmlDoc = HtmlPage.Document; HtmlPage.Window.Invoke("helloFromJS", message.Text);

  10. This code instantiates an HtmlDocument object which is a reference to the hosting HTML page. It then utilizes the Window.Invoke method to call a JavaScript method named helloFromJS and pass in the text in the Silverlight textbox control named message.
  11. This completes the coding, so hit F5 to test out the solution. After Visual Studio launches the browser, navigate to https://intranet.contoso.com/sites/htmlbridge/SitePages/SilverlightApplication1WebPartPage.aspx.
  12. Click the Say Hello via JavaScript button to test the code. Your screen should look like this:

    Figure 10

    Message dialog

Exercise 3 Verification

In order to verify that you have correctly performed all steps of exercise 3, proceed as follows:

Verification 1

In this verification, you can compare the anticipated output shown in step 8 with the actual output shown on your screen. If your screen shows a similar view, you have completed the exercise successfully.