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

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

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

Published Thursday, December 04, 2008 9:18 AM by Alex Golesh

Comments

# Silverlight Cream for December 06, 2008 -- #446

In this issue: Alex Golesh, Bart Czernicki, Matthias Shapiro(3), Michael WOlf, Swiss MSDN Team Blog,

Saturday, December 06, 2008 11:42 PM by Community Blogs

# 2008 December 08 - Links for today « My (almost) Daily Links

Pingback from  2008 December 08 - Links for today « My (almost) Daily Links

Leave a Comment

(required) 
(required) 
(optional)
(required)