Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Adding a Javascript Block Into a Form Hosted by WebBrowser Control

5.00/5 (3 votes)
18 Jul 2010CPOL1 min read 19.8K  
How to add a JavaScript block into a WebBrowser control

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:

JavaScript
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domElement = (IHTMLScriptElement)script.DomElement;
domElement.text = // put your script here;
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.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)