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:
<code class="language-csharp">HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];</code>
Create a script element using the CreateElement
method:
<code class="language-csharp">HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");</code>
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:
<code class="language-csharp">IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;</code>
Set the text
attribute to the desired JavaScript code:
<code class="language-csharp">element.text = "function sayHello() { alert('hello') }";</code>
Append a script element to the head
element to inject script into the DOM:
<code class="language-csharp">head.AppendChild(scriptEl);</code>
To execute the injected JavaScript function, call the Document
method on the WebBrowser control's InvokeScript
object:
<code class="language-csharp">webBrowser1.Document.InvokeScript("sayHello");</code>
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!