1: Introduction

.NET 2.0 has a new WebBrowser control in the System.Windows.Forms namespace. This control itself is very useful, but doesn't supply some events that might be needed in certain situations. This article explains how to extend the WebBrowser control and add functionality for things like pop-up blocking, script error handling, and handling new windows in a tabbed browser environment.

For extending the WebBrowser control, some features are not documented in the Help files of the .NET Framework. Not letting us be stopped by the "This method supports the .NET Framework infrastructure and is not intended to be used directly from your code." message, it is possible to create an object that implements IWebBrowser2 and use all the functionality of the underlying browser. Besides this, DWebBrowserEvents2 can be implemented for adding events to the control.

This article assumes that you have already some knowledge of the browser interfaces IWebBrowser2 and DWebBrowserEvents2. Some knowledge about COM Interop and interfaces is also required.

2: The goals, challenges, and solutions

The goals of this component are:

Handling script errors in a neat way

Blocking unwanted pop-ups

Enabling functionality for tabbed browsing or MDI browsing

Making sure that a window is closed when it is closed by script

This section explains the problems associated with the goals and their solutions, in a short form. The next section goes more into the coding details.

Handling Script Errors

The WebBrowser control has a ScriptErrorsSuppressed property... Setting this property to true does actually a bit more than it is supposed to. It not only disables the script error dialog, but also the dialog for logging on to a secure website with user certificates... What if we still want that functionality, or we would like to be notified when a script error has taken place, or we would like to know all the details about the script error?

The script error can be caught by the HtmlWindow.Error event. This event fires whenever a script error occurs, with all the details. The challenge is that HtmlWindow is to be accesed with the HtmlDocument object, which is not always available. HtmlDocument comes available as soon as the Navigated event is fired. But what if the user refreshes the browser with F5? Sorry, the Navigated event doesn't fire. After some testing, I found that the only reliable way was to use the DownloadComplete event, which is not part of the default WebBrowser control.

Solution:

Implement DWebBrowserEvents2

Create a DownloadComplete event

When DownloadComplete fires, subscribe to the HtmlWindow.Error event

Use the error event for obtaining the script error information

Set the Handled property to true to suppress the script error

Blocking unwanted pop-ups

Pop-ups are most of the time not very welcome, or could be inappropriate. To block these things, some additional information is needed. NewWindow3 gives this information when the user uses Windows XP SP2, or Windows 2003 SP1 or better. If this event is not fired, NewWindow2 takes its place. When NewWindow3 is fired, you can check:

If the user initiated the action that leads to the new window

If the user holds the override key (the Ctrl Key)

If it is a pop-up displayed because of a window that is closing

The URL that is going to be opened

And more...

Using NewWindow3 clearly is very interesting for this purpose. To use this event, DWebBrowserEvents2 needs to be implemented.

Solution:

Implement DWebBrowserEvents2

Create a new event and a new event arguments class

Launch this event with the appropriate information

After the event is fired, see if the navigation needs to be canceled

Enabling functionality for tabbed browsing or MDI browsing

Tabbed browsing seems to gain popularity these days. For Internet Explorer 7, this is one of the new features. The challenge in tabbed browsing is that you need to create a window when this is needed by scripts or links. Besides this, window name resolution should work over multiple windows or tabs. (For example: <A href="http://SomeSite" target="SomeWindowName"/>) To achieve this, the automation object (called ppDisp in the NewWindowX event, and Application in the IWebBrowser2 interface) should be passed from the new browser back to the event. To get access to the Application property, it is needed to get a reference to the underlying IWebBrowser2 interface.

Solution:

Override AttachInterfaces and DetachInterfaces

Store a reference to the IWebBrowser2 interface object

Create a property called Application that exposes the Application property of the interface

Implement the DWebBrowserEvents2 interface

Listen for NewWindow2 and/or NewWindow3 events

Whenever an event is raised, create a new instance of the browser control

Assign the event parameter ppDisp to the Application property of the new instance

Making sure that a window is closed when it is closed by script

When you invoke window.close() in JScript, it looks like the WebBrowser control hangs. Somehow, it can't be used for navigation, nor can it be used for anything else. It would be nice if we know when this happens. There are several events that fire when this happens, but none of the events gives us actually the information needed. Overriding WndProc and seeing if the parent is notified that the browser is destroyed, is the only reliable solution. (If someone knows how to get WindowClosing to work, it would be nice here!)

Solution:

Override WndProc

Check for the message WM_PARENTNOTIFY

Check for the parameter WM_DESTROY

If this is the case, fire a new event (this event is called Quit, in the example)

3: Creating the extended WebBrowser component

From the last section, we have seen that all of this basically comes down to two things:

Implement an object of type IWebBrowser2, for obtaining the Application property of the browser

Implement DWebBrowserEvents2 for firing events

Implementing IWebBrowser2

The WebBrowser control has two methods that are undocumented: AttachInterfaces() and DetachInterfaces(). These methods need to be used when you want to obtain a reference to the IWebBrowser2 interface.

///<spanclass="code-SummaryComment"><summary></span>/// An extended version of the <spanclass="code-SummaryComment"><seecref="WebBrowser"/> control.</span>///<spanclass="code-SummaryComment"></summary></span>publicclass ExtendedWebBrowser : System.Windows.Forms.WebBrowser
{
private UnsafeNativeMethods.IWebBrowser2 axIWebBrowser2;
///<spanclass="code-SummaryComment"><summary></span>/// This method supports the .NET Framework
/// infrastructure and is not intended
/// to be used directly from your code.
/// Called by the control when the underlying
/// ActiveX control is created.
///<spanclass="code-SummaryComment"></summary></span>///<spanclass="code-SummaryComment"><paramname="nativeActiveXObject"></param></span> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protectedoverridevoid
AttachInterfaces(object nativeActiveXObject)
{
this.axIWebBrowser2 =
(UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject;
base.AttachInterfaces(nativeActiveXObject);
}
///<spanclass="code-SummaryComment"><summary></span>/// This method supports the .NET Framework infrastructure
/// and is not intended to be used directly from your code.
/// Called by the control when the underlying
/// ActiveX control is discarded.
///<spanclass="code-SummaryComment"></summary></span> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protectedoverridevoid DetachInterfaces()
{
this.axIWebBrowser2 = null;
base.DetachInterfaces();
}
...
}

This property can be used for creating a new window, and redirecting the browser to this new window, when a new window event is fired.

Implementing DWebBrowserEvents2

The following events are implemented in this sample:

NewWindow2 and NewWindow3 (for blocking pop-ups and creating new windows)

DownloadBegin and DownloadComplete (for handling script errors)

BeforeNavigate2 (if you want to see where you're going before even starting to get there)

To neatly implement DWebBrowserEvents2, it is best to create a privately nested class in the component. This way, all the events that are needed are on one place and easy to find. When we instantiate this class, we provide a reference to the caller, whose methods can be invoked for raising the events we need.

Events are not attached at component construction, but a bit later. There are two methods here that provide this and can be overridden. These are CreateSink() and DetachSink(). When adding this all up, we get something like this (note that some code has been cut for readability):

4: Using the component

In the last section, we created a new component. Now, it's time to use the new events and get the maximum functionality out of the browser. For each of the goals, the details are explained here.

Handling the script errors

In the sample application, there is a tool window that simply shows a list of errors that occured, with their details. A single-instance class holds the script errors' information and notifies the subscribers when this information has been changed. For handling these script errors, the BrowserControl first attaches to the DownloadComplete event, and next subscribes to the HtmlWindow.Error event. When this event is fired, we register the script error and set the Handled property to true.

Handling pop-ups should be user configurable. For the purpose of demonstration, I've implemented four levels, ranging from blocking nothing to blocking every new window. This code is part of the BrowserControl, and shows how to do this. After the new window is allowed, the example shows how to let the new browser participate in the window name resolution.

void _browser_StartNewWindow(object sender,
BrowserExtendedNavigatingEventArgs e)
{
// Here we do the pop-up blocker work// Note that in Windows 2000 or lower this event will fire, but the// event arguments will not contain any useful information// for blocking pop-ups.// There are 4 filter levels.// None: Allow all pop-ups// Low: Allow pop-ups from secure sites// Medium: Block most pop-ups// High: Block all pop-ups (Use Ctrl to override)// We need the instance of the main form,// because this holds the instance// to the WindowManager.
MainForm mf = GetMainFormFromControl(sender as Control);
if (mf == null)
return;
// Allow a popup when there is no information// available or when the Ctrl key is pressedbool allowPopup = (e.NavigationContext == UrlContext.None)
|| ((e.NavigationContext &
UrlContext.OverrideKey) == UrlContext.OverrideKey);
if (!allowPopup)
{
// Give None, Low & Medium still a chance.switch (SettingsHelper.Current.FilterLevel)
{
case PopupBlockerFilterLevel.None:
allowPopup = true;
break;
case PopupBlockerFilterLevel.Low:
// See if this is a secure siteif (this.WebBrowser.EncryptionLevel !=
WebBrowserEncryptionLevel.Insecure)
allowPopup = true;
else// Not a secure site, handle this like the medium filtergotocase PopupBlockerFilterLevel.Medium;
break;
case PopupBlockerFilterLevel.Medium:
// This is the most dificult one.// Only when the user first inited// and the new window is user initedif ((e.NavigationContext & UrlContext.UserFirstInited)
== UrlContext.UserFirstInited &&
(e.NavigationContext & UrlContext.UserInited)
== UrlContext.UserInited)
allowPopup = true;
break;
}
}
if (allowPopup)
{
// Check wheter it's a HTML dialog box.// If so, allow the popup but do not open a new tabif (!((e.NavigationContext &
UrlContext.HtmlDialog) == UrlContext.HtmlDialog))
{
ExtendedWebBrowser ewb = mf.WindowManager.New(false);
// The (in)famous application object
e.AutomationObject = ewb.Application;
}
}
else// Here you could notify the user that the pop-up was blocked
e.Cancel = true;
}

The reason the event is called StartNewWindow is that the code design guidelines do not allow an event to begin with "Before" or "After". "NewWindowing" doesn't have the same kind of ring to it :)

Using the Quit event

When the Quit event is fired, it's simply a matter of finding the right window or tab to close, and Dispose the instance.

5: Conclusion

The WebBrowser control is a good control for enabling web content in Windows applications. The additions in this article can be used to overcome the obstacles that developers face when they have no control over what web pages or other content the user might visit with their application. Hopefully, the next version of the .NET Framework will give us a little extra.

The sample application and source

The sample application is not a flashy UI, but it does demonstrate everything about this article. The code is commented, and hopefully gives enough information for helping you put your own solution together.

Acknowledgements

I would like to thank the following persons that made part of this article possible:

The technique for DWebBrowserEvents2 was in the bug list of Microsoft .NET 2.0. This has been used with modification.

The technique for WndProc was told by someone called "JoeBlow" on the MSDN forums, who had it derived from the MSKB article #253219.

This is my first article on The Code Project. Please excuse me for my English. Thanks for reading! If you can add anything or have suggestions or tips, please post a message below.

License

The code in this license may be used for any purpose, just let your users know where it came from, and share derived code under the same license as this one. Don't blame me if something goes wrong. More information can be found here.

If you wish to use and/or publish this in commercial closed-source applications, you have my consent. You may use this code under your own license when you do so.

History

27th of March 2006: First post of this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

I am
- born in The Netherlands
- living in Chile together with my wife.
- a Microsoft Certified Professional Developer on all 3 areas (Windows, Web and Enterprise)
- an MCITP on Microsoft SQL Server 2005 (Database Administrator)
- an active programmer for about 14 years.
- a business owner, of a Dutch company called "The Wheel Automatisering" (http://www.thewheel.nl)
- a coder in C#, VB.Net and Managed C++.
- someone who likes to share knowledge

For fun I like to go out with my dogs, enjoy the sun or write some articles that I share with the community.

Many picture album websites show pictures in a secondary window using links specifying a target window by name. The browser opens the picture URL in a new window and subsequent references to the same name resolve to the same browser window. In your tabbed browser, however, a new tab is created for each picture link clicked. I notice the Document.Window.Name for the newly created browser tab is set properly, apparently after the return from NewWindow3. But NewWindow3 doesn't seem to contain enough info (like the target name) to allow us to resolve this ourselves and return the same window for subsequent NewWindow requests.

The lack of target information certainly seems to be a significant omission in NewWindow3. Anyone been able to find a resolution to this? If I'm using NewWindow3 to enable tabbed browsing I should be able to use any target information from the link to ensure that the same tab is reused if appropriate.

Is there a way to load something like an internal (in memory) host file so that I can map host names to different ips without the user having to change their host files? When we do testing we usually change the host files to point to the test server. That way the urls can stay the same as in production but allow us to test a different version of the site. The users get confused about host files so I thought I create a browser application for them and control this myself.

Ctrl+N is a shortcut in Internet Explorer, you'd need to suppress the key sequence if you want to do anything about it.

Try going here to resolve this problem. It links to a project that Emma Burrows wrote. It has an example of how to lock Control key sequences down. I've implement a version of this solution, and NOTHING is allowed. No Alt-Tab, Ctrl-N, or anything (except Ctrl-alt-delete) is accepted as valid key presses. And the code is very quick too. Hope it helps!

Is there any way to block the new window from javascript? There is a website for popup blocker test: http://www.popuptest.com/. The third test 'Come & Go Test' use javascript to open a new window. It didn't fire the new window event.

Is there a way to get to the DOM tree *before* the document is rendered?

Basically, I want to be able to strip out / change some code before the document is displayed to the user. Right now, the user could click on a link before the DocumentComplete event is fired and navigate away before the document completes loading, and I need to prevent this.

Try to use the DownloadComplete event for this. This will fire multiple times (depending on frames, pictures, etc). This event is fired every time a part of the document has been downloaded. The first time this is fired should is right after the primary document HTML has been downloaded.

Thank you for your comments. The problem in this case is that the document contains an IFrame, which loads a document with a JScript error. Since the error event is only monitored on the main document, the error of the IFrame document displays the error dialog.

I'll make an update to resolve this issue and post this within the next week.

i suppose the document_completed event isnt triggered already. maybe the site is still loading other frames (so document_completed isn't triggered so far) but the frame with the script error on it has already completed - so the script error is shown.

do you have any hint how to get rid of it without setting the badly named property "ScriptErrorsSuppressed" ?
thanks, tob

I have noticed there are circumstances under which the DocumentComplete event is not triggered. I have not researched this yet, but it is not (entirely) dependent on the webpage being loaded but rather perhaps on the kind of action which causes it to be loaded. I'm tempted to just add this "Error Event Hookup" call to any and every event that's triggered with a document in context. (Perhaps even a timer!!)

There is one other problem of interest I did solve. The page can be visible long before DocumentComplete triggers where even the most innocent of actions such as mouse rollover can cause script errors. I added an "Error Event Hookup" call to the NavigateComplete2 event, which helps greatly. But that's very sensitive to timing as to how much is loaded by then and so requires a followup at some later event.

I will apologize in advance for asking a question that has nothing to do with this project, but you seem to have experience with the .NET 2.0 Webbrowser control and I have not been able to get an answer any where.

Dev env: VS 2005 C# Express, .Net Framework 2.0

I am trying to programmatically select an item in a listbox on a web page. The first thing I do is go through and de-select any selected items. The OuterHtml field of a selected element in the listbox looks something like this:

Default item

I want to simply remove the the term 'selected' this way:

elt.OuterHtml = elt.OuterHtml.Replace("selected","");

This results in OuterHtml being set to:

Notice: 1) the 'selected' term is untouched, 2) the visible text has been removed.

After the assignment I can see in the debugger that one of the members of the HtmlElement object (OffsetParent, I think) has a string indicating some kind of COM Interop services exception.

The MSDN documentation at

http://tinyurl.com/edbln

does contain this warning:

"If you assign a new value to OuterHtml, the current element reference will become invalid; it will not reflect the name, properties and child content of the HTML you have just assigned."

but I don't really understand what that means.

Is it possible to change the HTML in a web page? Am I going about it the wrong way? Is there some kind of initialization or setup call I am supposed to make? Is it just a bug in .NET 2.0?

If you're trying to do this from JScript, you simply can change the options collection to add/remove options and set the selectedIndex property to determine which options is selected.

If you want to do this from C# (i.e. access the DOM from the WebBrowser control) then you need to reference the Microsoft.MSHTML assembly, cast from Document.DOMDocument to IHtmlDocument2 and access the option group from there. This works similar like JScript, only then in C# with the supplied object model in MSHTML.

In either case, it's not needed to change the outerHtml property of the listbox, simply use the selectedIndex property.

I’m searching the internet for a solution to resolve the session problem in the AxSHDocVw.AxWebBrowser and I don’t find anything. I just found your ExtendedWebControl and it looks very nice. I figured out there is the same problem. When login in to gmail and then I open a second window and go to www.gmail.com, I will be logged in as well. This effect is not useable for me, because I would like on each window a different user login.
I now, that is not right spot to send this message, but we will upgrade to SDK 2.0 soon and than I could use the webcontrol from the framework. To bad that doesn’t solve my problem.

This issue remains, since I haven't been able to get the WindowClosing event to work. (Even not with the workarounds available for the .Net framework 1.x) As soon as someone figures that out, then window.close could be canceled.

The procedure that you specified, is called after the window is "destroyed". This is allready a step too late...