Inject JavaScript code into the WebBrowser control in C#
This article describes a technique for injecting JavaScript code into the WebBrowser control Document Object Model (DOM). This approach stems from the difficulty of manipulating script elements directly using the InnerHtml
attribute.
The following steps will guide you through the process:
Get the head
element of the current document in the WebBrowser control:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
Create a script element using the CreateElement
method:
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
Converts script elements into IHTMLScriptElement
interfaces. This step is crucial because it allows access to the interface that defines the "text" attribute of the script element:
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
Set the text
attribute to the desired JavaScript code:
element.text = "function sayHello() { alert('hello') }";
Append a script element to the head
element to inject script into the DOM:
head.AppendChild(scriptEl);
To execute the injected JavaScript function, call the Document
method on the WebBrowser control's InvokeScript
object:
webBrowser1.Document.InvokeScript("sayHello");
With this method, you can inject JavaScript code into the DOM of the WebBrowser control, thereby dynamically modifying its functionality and behavior.
The above is the detailed content of How to Inject JavaScript into a WebBrowser Control Using C#?. For more information, please follow other related articles on the PHP Chinese website!