Introduction
Today I found myself with a need to add a JavaScript block into a WebBrowser control in order to do some work. This post will show you the steps to do exactly that.
The Problem
In a project I'm consulting for, there was a need to dynamically add a JavaScript block into a web form that is hosted inside a WebBrowser control. So what can we do?
The Solution
We can use the Microsoft HTML Object Library to achieve the task. The Microsoft HTML Object Library is a COM library that you can reference in order to create HTML elements to use in the WebBrowser control. You first need to reference it so go to the COM tab in Add Reference view, search it and reference it. Now you can use the following code in order to add your script to the head section of the HTML:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domElement = (IHTMLScriptElement)script.DomElement;
domElement.text =
head.AppendChild(script);
Pay attention to replace the comment with your script implementation.
Summary
Using Microsoft HTML Object Library with the WebBrowser can help you to achieve the insertion of JavaScript to a web form which is hosted inside the control. It also enables creating and appending other HTML elements and can be useful for other tasks.
CodeProject