Silverlight Tip: How to Inject and Execute JavaScript Function(s) on-the-fly from Silverlight

December 4, 2008

Today I’ve been asked by colleague how to inject and execute JavaScript functionality from Silverlight application to the HTML DOM of hosting page.

Well, things are pretty easy. First we need to get JavaScript from somewhere. In colleague’s case it was an embedded resource, in my sample I’ll use TextBox to accept the script code. Also I’ll accept function name and parameters from UI.

image

From here we have two approaches: to Eval the function code or to create “Script” element dynamically.

First approach is very straightforward:

string src = txtScript.Text;
HtmlPage.Window.Eval(src);

Second approach is pretty much of the same, but creates a real “Script” block in the document’s body:

HtmlElement Script = HtmlPage.Document.CreateElement("script");
Script.SetAttribute("type", "text/javascript");
Script.SetProperty("text", txtScript.Text);
 
HtmlPage.Document.DocumentElement.AppendChild(Script);

Now all we have to do is execute the function:

string funcParames = null;
 
if (txtFunctionParams.Text.Length > 0)
    funcParames = txtFunctionParams.Text;
 
HtmlPage.Window.Invoke(txtFunctionName.Text, funcParames);

That’s it… Running application here:

Dynamic JavaScript Injection and Execution with Silverlight

 

Sure this application is pretty simple and unsecure, but this is only a demo and could be enriched with any needed functionality.

Sources here.

 

p.s. Noam – many thanks for idea ;)

 

Enjoy,

Alex

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

one comment

  1. Ricardo Nuno AlmeidaApril 22, 2011 ב 11:31

    Thank you for the succinct and straight-to-the-point article. Examples helped a lot.
    PS: check your hosted resources, links seem broken.

    Reply