I\'ve tried this:
string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName(\"head\")[0];
HtmlElement scriptEl = browser
If all you really want is to run javascript, this would be easiest (VB .Net):
MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();")
I guess that this wouldn't "inject" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function "foo" and let the javascript do the injection for you.
I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.
In this example the javascript code is injected and executed at global scope:
var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
If you want to delay execution, inject functions and call them after:
var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});
This is valid for Windows Forms and WPF WebBrowser controls.
This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.
For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).
var jsCode="alert('hello world');";
(new Function(code))();
Of course, you can delay execution:
var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();
Hope it helps
i use this:
webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" })