2

I am trying to have a method in my code behind at runtime add a function at runtime. I can dynamically add elements to my document with no problem. So I tried the same strategy for adding a script block.

Here's what I have tried thus far with no luck. It can create the script block but when I try to add the function. The only thing I can gather is that since the page is loading, it can't add the JS method. I am trying to add this before the page is loaded. So I figured I would be able to add script. If I can't add a function, I would like to at least feed it some javascript in my code behind to invoke at runtime.

Here is how I try to dynamically add the script block... which throw a runtime error on the SetProperty() method.

HtmlElement script = HtmlPage.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.SetProperty("innerHTML", "function testing() { alert('hello world'); }");
HtmlPage.Document.Body.AppendChild(script);

Then to invoke an EXISTING function on the document this works...

HtmlPage.Window.Invoke("testing2");

If I can't dynamically add a script block could I somehow invoke some javascript from my code behind?

Thanks!!!

1
  • I had this same problem: this code seems to work in most browsers but in IE8 and earlier it blows up. Your solution of setting text instead of innerHTML works great. Commented Feb 13, 2013 at 23:16

1 Answer 1

4

Well I figured out how to Invoke some script from the code behind...

Here's how to invoke some script at run-time

HtmlPage.Window.Eval("window.close();");

Here is a way to dynamically create JavaScript functions and add them to your page to use in silverlight applications.

// Create the script block
var scriptElement = HtmlPage.Document.CreateElement("script");
scriptElement.SetAttribute("type", "text/javascript");
// Add a function called foo
scriptElement.SetProperty("text", "function foo() { alert('hello foo!'); } ");
// Append script block to the body of the page
HtmlPage.Document.Body.AppendChild(scriptElement);


// Now invoke the function from your silverlight application
HtmlPage.Window.Invoke("foo", null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.