Home >Backend Development >C++ >How to Safely Inject JavaScript into a WebBrowser Control?
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>Create a script element and specify its type:
<code class="language-csharp">HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); scriptEl.SetAttribute("type", "text/javascript");</code>IHTMLSCRIPTELEMENT interface to get the script element:
<code class="language-csharp">IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;</code>Set the text attribute of IHTMLSCRIPTELEMENT to define JavaScript code:
<code class="language-csharp">element.text = "function sayHello() { alert('hello') }";</code>Attach the script element to Head element:
<code class="language-csharp">head.AppendChild(scriptEl);</code>JavaScript function calls from Webbrowser control:
<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!