Skip to content Skip to sidebar Skip to footer

How To Inject Javascript In Webbrowser Control?

I've tried this: string newScript = textBox1.Text; HtmlElement head = browserCtrl.Document.GetElementsByTagName('head')[0]; HtmlElement scriptEl = browserCtrl.Document.CreateElemen

Solution 1:

For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:

HtmlElementhead= webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElementscriptEl= webBrowser1.Document.CreateElement("script");
IHTMLScriptElementelement= (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

This answer explains how to get the IHTMLScriptElement interface into your project.

Solution 2:

HtmlDocumentdoc= browser.Document;
HtmlElementhead= doc.GetElementsByTagName("head")[0];
HtmlElements= doc.CreateElement("script");
s.SetAttribute("text","function sayHello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");

(tested in .NET 4 / Windows Forms App)

Edit: Fixed case issue in function set.

Solution 3:

Here is the easiest way that I found after working on this:

string javascript = "alert('Hello');";
// or any combination of your JavaScript commands// (including function calls, variables... etc)// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", newobject[] { javascript });

What global JavaScript function eval(str) does is parses and executes whatever is written in str. Check w3schools ref here.

Solution 4:

Also, in .NET 4 this is even easier if you use the dynamic keyword:

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

Solution 5:

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.

Post a Comment for "How To Inject Javascript In Webbrowser Control?"