Tutorials » Silverlight tutorials »

How to call Javascript functions from Silverlight code ?

This Silverlight shows sample how to call Javascript functions from Silverlight controls code behind file

One of the advantages of Silverlight is, it has access to the Html document of the web page in which it is hosted. This enables Silverlight to access HTML elements in the page and also call Javascript methods.

The following steps shows how to call a Javascript method from Silverlight.

Open the ASP.NET or HTML page which hosts the Silverlight control. Add the Javascript method as shown below:

<script language="javascript"≫
function SayHello()
alert("Hello from JavaScript, invoked by Silverlight");

Now, open your XAML control file and add a button control as shown below:

<Grid x:Name="LayoutRoot" Background="White">
<Button x:Name="btnSayHello" Content="Say Hello"

Go to the code behind file for the XAML Page and add the event handler for the button click event:

private void btnSayHello_Click(object sender, RoutedEventArgs e)

In order to use the HtmlPage class, you need to include the System.Windows.Browser

using System.Windows.Browser;

You are done. Run your Silverlight application and see. When you click on the button in the Silverlight control, you can see the popup message from the Javascript function.

You can download a sample project for this tutorial.

Next Chapter: How to show a popup layer within a Silverlight web page?
Previous Chapter: Create WCF service to retrieve session data - part II
More Chapters: Silverlight Tutorials
More Tutorials: Tutorial Index

Top Contributors
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India