Home >Backend Development >C++ >How to Inject JavaScript into a WebBrowser Control Using C#?

How to Inject JavaScript into a WebBrowser Control Using C#?

DDD
DDDOriginal
2025-01-26 21:26:16582browse

How to Inject JavaScript into a WebBrowser Control Using C#?

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:

  1. Get the head element of the current document in the WebBrowser control:

    <code class="language-csharp">HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];</code>
  2. Create a script element using the CreateElement method:

    <code class="language-csharp">HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");</code>
  3. 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>
  4. Set the text attribute to the desired JavaScript code:

    <code class="language-csharp">element.text = "function sayHello() { alert('hello') }";</code>
  5. Append a script element to the head element to inject script into the DOM:

    <code class="language-csharp">head.AppendChild(scriptEl);</code>
  6. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn