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
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net