Injecting JavaScript into the Webbrowser control is an effective technique of the webpage function displayed in the control control. However, the InnerHTML property of the HTMLELEMENT object may cause System.notsupportedException error.
In order to effectively inject JavaScript, different methods need to be used. The following steps outline the solution:
Get the wead element of the webpage in the webbrowser control:
<code class="language-csharp">HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];</code>
<code class="language-csharp">HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); scriptEl.SetAttribute("type", "text/javascript");</code>
<code class="language-csharp">IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;</code>
<code class="language-csharp">element.text = "function sayHello() { alert('hello') }";</code>
<code class="language-csharp">head.AppendChild(scriptEl);</code>
<code class="language-csharp">webBrowser1.Document.InvokeScript("sayHello");</code>
The above is the detailed content of How to Safely Inject JavaScript into a WebBrowser Control?. For more information, please follow other related articles on the PHP Chinese website!