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
Release: 2025-01-26 21:26:16
Original
576 people have browsed it

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>
    Copy after login
  2. Create a script element using the CreateElement method:

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

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

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template