Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



Silverlight: Load JavaScript from Embedded Resource and Execute Within Page

I've been playing around with Silverlight 2 Beta 1 alot lately, and one of the areas I've been focusing on is interoperability with JavaScript and the DOM. Here's a technique I've found that allows you to inject JavaScript into the page from within your Silverlight application. This example also starts with the idea that the JavaScript you are going to inject is stored as an Embedded Resource within your Silverlight Application.

Step 1: Create your JavaScript (.js) file and add it as an embedded resource to your Silverlight Application.

Step 2: Place code in your app that loads the embedded JavaScript file to a string variable:

// Load JavaScript code from Embedded Resource
System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream("[namespace].[javascriptFileName]");
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string script = reader.ReadToEnd();

Note: Replace the [namespace] text above with the full namespace of your Silverlight application project. Also, replace the [javascriptFileName] text above with the filename of your JavaScript file. An example value for this with the namespace and JavaScript filename is "MyApplication.TestScript.js".

Step 3: Inject the JavaScript into the page using Eval:

HtmlPage.Window.Eval(script);

This is a small technique that I've found to make mixing JavaScript with Silverlight a little easier since this allows you to take advantage of JavaScript Intellisense within Visual Studio 2008; where if you just placed the JavaScript code inline within your C# or VB.NET code you would not be able to have JavaScript Intellisense.

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Silverlight
Posted by crpietschmann on Monday, May 19, 2008 8:32 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Comments are closed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann