Home > Web Front-end > JS Tutorial > How to Inject JavaScript into a WebBrowser Control Without Using InnerHtml?

How to Inject JavaScript into a WebBrowser Control Without Using InnerHtml?

Susan Sarandon
Release: 2024-11-19 18:45:03
Original
393 people have browsed it

How to Inject JavaScript into a WebBrowser Control Without Using InnerHtml?

Injecting JavaScript into a WebBrowser Control

Question:

I am trying to inject a JavaScript script into a WebBrowser control, but encountering errors when setting the InnerHtml property of the script element. Is there an alternative method to achieve this?

Answer:

虽然原始尝试未能成功,但可以使用以下方法将脚本注入 DOM:

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

Explanation:

  • Get IHTMLScriptElement Interface:

    • The DomElement property exposes the underlying COM object. Casting this to IHTMLScriptElement allows access to the text property.
  • Set Script Text:

    • Assign the desired JavaScript code to the text property.
  • Invoke Script:

    • Call InvokeScript on the document to execute the injected script.

The above is the detailed content of How to Inject JavaScript into a WebBrowser Control Without Using InnerHtml?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template