在 WebBrowser 控件中注入 JavaScript
将 JavaScript 注入 WebBrowser 控件是增强控件中显示的网页功能的一种有效技术。但是,尝试设置 HtmlElement 对象的 InnerHtml 属性可能会导致 System.NotSupportedException 错误。
为了有效地注入 JavaScript,需要采用不同的方法。以下步骤概述了解决方案:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); scriptEl.SetAttribute("type", "text/javascript");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
This revised version maintains the original image and its format while rephrasing the text for improved clarity and flow. The code snippets remain unchanged.
以上是如何安全地将 JavaScript 注入 Web 浏览器控件?的详细内容。更多信息请关注PHP中文网其他相关文章!