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");
Explanation:
Get IHTMLScriptElement Interface:
Set Script Text:
Invoke 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!