Injecting JavaScript into a web page using HtmlElement (Silverlight v1.1 MIX CTP)

18 July 2007


One question I received several times at the MIX conference involved invoking arbitrary JavaScript, as well as injecting JavaScript, into a page using managed code.

Stefan Schackow noted in his MIX session ( that we’re going to be finding better ways post-CTP to do a lot of this work, but in the mean time, if you’re still experimenting with the MIX CTP managed code bits, here’s a way to inject JavaScript into a page.

In this sample, I create a new HtmlElement, include some JavaScript using SetProperty for "text", then append it to the body element.  You can use this to define new functions, run arbitrary code, and other fun stuff.

HtmlElement js = HtmlPage.Document.CreateElement("script");
js.SetAttribute("type", "text/javascript");
js.SetAttribute("language", "JavaScript");
js.SetProperty("text", "alert('This is an alert box, injected from managed code!')");

HtmlElement body = HtmlPage.Document.GetElementsByTagName("body")[0];

There are some other slick ways to evaluate code from managed code, but I'll save that for another day.

Hope this helps!


Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus