By injecting the JavaScript code in the webpage, dynamic elements can be used to enhance the webpage function. However, the standard HTMLDOCUMENT method may encounter errors. This guide provides a solution to this problem.
The problem is located
The following code sample demonstrates the attempt to inject JavaScript into the document:
However, the InnerHTML attribute accessing Scriptel will throw the NotSupportedException exception. This shows that the HTMLEMENT type does not support the internal HTML for the script element.
<code>string newScript = textBox1.Text; HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = browserCtrl.Document.CreateElement("script"); lblStatus.Text = scriptEl.GetType().ToString(); scriptEl.SetAttribute("type", "text/javascript"); head.AppendChild(scriptEl); scriptEl.InnerHtml = "function sayHello() { alert('hello') }";</code>
In order to solve this problem, we need to access the underlying IHTMLSCRIPTELEMENT interface. The following updated code fragment demonstrates this method:
Explanation
<code>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");</code>
Get the head element of the document. Create a new script element.
The above is the detailed content of How to Correctly Inject JavaScript into an HTML Document to Avoid `NotSupportedException`?. For more information, please follow other related articles on the PHP Chinese website!