DCSIMG
Adding a Javascript Block Into a Form Hosted by WebBrowser Control - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Adding a Javascript Block Into a Form Hosted by WebBrowser Control

Adding a Javascript Block Into a Form Hosted by WebBrowser Control

Today I found myselfInjecting Javascript Into WebBrowser Control
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 = // 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 the creating and appending other HTML elements and can
be useful for other tasks.

Comments

Twitter Trackbacks for Adding a Javascript Block Into a Form Hosted by WebBrowser Control - Gil Fink on .Net [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Adding a Javascript Block Into a Form Hosted by WebBrowser Control - Gil Fink on .Net         [microsoft.co.il]        on Topsy.com

# July 14, 2010 7:48 PM

Adding a Javascript Block Into a Form Hosted by WebBrowser Control … – javascript - dowiedz si?? wi??cej! said:

Pingback from  Adding a Javascript Block Into a Form Hosted by WebBrowser Control … – javascript - dowiedz si?? wi??cej!

# July 14, 2010 10:14 PM

Adding a Javascript Block Into a Form Hosted by WebBrowser Control … « ??????????????????????????????????????? said:

Pingback from  Adding a Javascript Block Into a Form Hosted by WebBrowser Control … «  ???????????????????????????????????????

# July 15, 2010 7:29 AM