I am trying to have a method in my code behind at runtime add a function at runtime. I can dynamicall开发者_运维百科y 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!!!
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);
精彩评论