Chapter 15. Accessing Silverlight Content with JavaScript (and Vice Versa)

The previous parts of this book have used a lot of C# code to enrich XAML-based Silverlight applications. Here we will introduce a different approach. We will create a number of <something>.js files, or code-behind JavaScript files for the HTML document containing the Silverlight content, so to speak. The JavaScript code will access the Silverlight content, add new Silverlight elements, and read information about the plug-in or the content of the XAML file.

We will use the Script Web Visual Studio template as the basis for the examples in this part of the book. Of course, you can achieve everything we are covering in the chapters in this part of the book using the project template; however, it is a bit easier to inject JavaScript code in the Script Web template, since the sample page there is already using JavaScript code.

Accessing the Plug-in

To access Silverlight content embedded on a page, you first need to access the Silverlight plug-in. There are two ways to retrieve this information: access the plug-in from within the XAML event handler code or use the JavaScript Document Object Model (DOM). Let’s start with the latter option and look at the automatically generated (thanks to the template) JavaScript code to load Silverlight content:

Silverlight.createObjectEx({
  source: 'Scene.xaml',
  parentElement: document.getElementById('silverlightPlugInHost'),
  id: 'silverlightPlugIn', properties: { width: '100%', height: ...

Get Essential Silverlight 2 Up-to-Date now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.