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

Posted 18 July 2007  

[RAW]

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 (http://sessions.visitmix.com/) 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];
body.AppendChild(js);

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

Hope this helps!

[/RAW]

Jeff Wilcox is a Principal Software Engineer at Microsoft in the Open Source Programs Office, helping Microsoft scale to 10,000+ engineers using, contributing to and releasing open source.

comments powered by Disqus