Calling JavaScript functions from Silverlight 2

Posted by: Malcolm Sheridan , on 4/7/2009, in Category Silverlight 2, 3, 4 and 5
Views: 51454
Abstract: Silverlight 2 is a great technology to build business centric applications, and one of the coolest features is the ability to call JavaScript functions from your Silverlight code. The following article demonstrates how to use call JavaScript from Silverlight 2.
Calling JavaScript functions from Silverlight 2
Silverlight 2 is a great technology to build business centric applications, and one of the coolest features is the ability to call JavaScript functions from your Silverlight code. 
To begin with, Open Visual Studio 2008 and choose File > New > Project > Silverlight > Silverlight Application. In the web application, add a new JavaScript file to the project and name it MyFunctions.js. Add the following code to the JavaScript file:
function alertText(text) {
function sendText() {
    return "Hi from Javascript!";
The JavaScript code shown above is as basic as it gets, but the interesting part is not the JavaScript itself but how to call it from Silverlight. Open the Silverlight project and add the following xaml to the Page.xaml file:
<Grid x:Name="LayoutRoot" Background="Transparent">
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
            <ColumnDefinition Width="200"></ColumnDefinition>
            <ColumnDefinition Width="200"></ColumnDefinition>
        <Button x:Name="btnFireJavascript" Grid.Column="0" Click="btnFireJavascript_Click" Width="100" Height="30" Content="Send Data!"></Button>       
        <Button x:Name="btnReceiveJavascript" Click="btnReceiveJavascript_Click" Grid.Column="1" Width="100" Height="30" Content="Receive Data!"></Button>
        <TextBox x:Name="txtReturnData" Height="30" Width="150" Grid.Row="1" Grid.ColumnSpan="2"></TextBox>
In the .xaml above, I have created a Grid with two columns and two rows. There are two buttons and one text box. Right click on the btnFireJavascript_Click event handler. The code behind file will open. Add the following code:
HtmlPage.Window.Invoke("alertText", new string[] { "Hi!" });
HtmlPage.Window.Invoke("alertText", New String() { "Hi!" })
The code that is doing all the work for you is HtmlPage.Window.Invoke. The HtmlPage class allows you the developer, to access and manipulate the browsers Document Object Model (DOM). The Window property returns a reference to the HtmlWindow class. This class provides a managed representation of the JavaScript window object. The Invoke method invokes a JavaScript function and optionally passes an array of parameters. In the code above, the first parameter, alertText, is the name of the JavaScript function. The second parameter is the arguments that are passed to the function.
Moving back to the .xaml, I have defined a button that will receive data returned from a JavaScript function. Right click on the btnReceiveJavascript_Click event handler. The code behind file will open. Add the following code:
string obj = HtmlPage.Window.Invoke("sendText", null) as string;
txtReturnData.Text = obj;
Dim obj As String = TryCast(HtmlPage.Window.Invoke("sendText", Nothing), String)
txtReturnData.Text = obj
In the code above, the Invoke method invokes the JavaScript function, but the return type from the function is a string. Invoke returns an object type, so we must cast the returned value to a string. The string is then set to be displayed in the text box. The final piece of code to add before running the project is a 'using' statement to the top of your code behind file:
using System.Windows.Browser;
Imports System.Windows.Browser
The HtmlPage and HtmlWindow reside in the System.Windows.Browser namespace.
Run the project and you’ll be able to invoke JavaScript functions and return values from the function. Personally I think this is great functionality if you’re building business centric applications. This way, you could harness the power of jQuery in your project. In part II of this article, I’ll take this sample and enhance it so it can perform day to day business functions using Silverlight and jQuery. Stay tuned!
The source code of this article can be downloaded from here.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email  
Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET. 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by David on Tuesday, April 14, 2009 11:26 AM
I tried your code and it does not work.  I get the following error:  "Failed to Invoke: alertText"
Comment posted by Malcolm Sheridan on Tuesday, April 14, 2009 9:07 PM
Make sure you have a reference to the JavaScript file in your web page.  You need that otherwise the code will not work.  I left that out of the example but it is in the source code that is freely available.
Comment posted by aesha on Thursday, June 11, 2009 7:42 AM
How to make reference to javascript file in our web page?
Comment posted by Suprotim Agarwal on Monday, June 15, 2009 9:27 AM
Aesha: Check these two articles of mine to figure this out
Comment posted by Sharadindu Basuli on Tuesday, May 4, 2010 2:11 AM
I tried ur code but not working.
Comment posted by dotnetflavors on Friday, November 18, 2011 5:03 AM
see this link: (or)
Comment posted by Ruchita Kadam on Saturday, February 9, 2013 5:44 AM

I am using Silverlight 5 & hence I want to know how can we call JavaScript functions from Silverlight 5.
Actually, I have .js files which I want to use or embed in my silverlight page..
Please provide solution to my problem!! :)

Comment posted by vivek gupta on Wednesday, July 3, 2013 5:50 AM
regarding...Calling JavaScript functions from Silverlight 2

do we need to register .js file in xaml page
Comment posted by vivek Gupta on Wednesday, July 3, 2013 6:39 AM
It worked ..Thanks a lot :-)