Calling JavaScript functions from Silverlight 2

Posted by: Malcolm Sheridan , on 4/7/2009, in Category Silverlight 2, 3, 4 and 5
Views: 40529
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) {
    alert(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">
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"></ColumnDefinition>
            <ColumnDefinition Width="200"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <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>
    </Grid>
 
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:
 
C#
 
HtmlPage.Window.Invoke("alertText", new string[] { "Hi!" });
 
VB.NET
 
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:
 
C#
 
string obj = HtmlPage.Window.Invoke("sendText", null) as string;
txtReturnData.Text = obj;
 
VB.NET
 
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:
 
C#
 
using System.Windows.Browser;
 
VB.NET
 
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. 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
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


User Feedback
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
@David
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

www.dotnetcurry.com/ShowArticle.aspx?ID=273
www.dotnetcurry.com/ShowArticle.aspx?ID=274
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:http://dotnetflavors.blogspot.com/ (or) http://dotnetflavors.blogspot.com/2011/10/calling-javascript-function-from-code.html
Comment posted by Ruchita Kadam on Saturday, February 9, 2013 5:44 AM
Hello,

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!! :)

Thanks,
Ruchita
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 :-)

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel