【翻译】扩展 .NET 2.0 WebBrowser控件

【翻译】扩展 .NET 2.0 WebBrowser控件

原文地址:http://www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx

目录

1、  简介

2、  目标、挑战和解决方案

l  捕获脚本错误

l  过滤弹出窗口

l  添加多标签页或多窗口浏览功能

l  当一个窗口是由脚本关闭时,需要确认

3、  创建WebBrowser扩展控件

l  实现 IWebBrowser2接口

l  实现 DWebBrowserEvents2接口

4、  使用该扩展控件

l  捕获脚本错误

l  过滤弹出窗口并添加多标签页或多窗口浏览功能

l  使用退出事件

5、  结束语

l  示例程序和源代码

l  知识库

l  许可

l  历史版本

 

1、  简介

 

.Net 2.0System.Windows.Forms命名空间中新增了WebBrowser控件,该控件本身是非常有用的,但是它没有提供在某些情况下需要的事件。这篇文章描述了如何扩展WebBrowser控件并增加一些功能,例如:屏蔽弹出窗口、捕获脚本错误以及捕获新窗口并将其显示在多标签浏览窗口环境中。
 

在扩展WebBrowser控件时,某些功能没有写入.Net Framework的帮助文件,不用理会“这个方法是用于支持.Net基础架构的,不推荐直接用于您的代码中”的提示信息,我们可以创建一个实现IWebBrowser2接口的对象,并使用浏览器对象的全部功能,此外,使用DWebBrowserEvents2接口可以向控件中添加事件。

 

这篇文章假设你已经了解了IWebBrowser2接口和DWebBrowserEvents2接口,对COM的互操作和相关的接口知识也是需要了解的。

 

2、  目标、挑战和解决方案

 

这个组件要实现的目标是:

l  用简洁的方式捕获脚本错误

l  过滤弹出窗口

l  加入多标签页浏览或多窗口浏览功能

l  当窗口被脚本关闭时需要确认

 

这一节简要讲解实现这些目标所遇到的问题和相关的解决方案,下一节中会给出更多的代码细节。

 

捕获脚本错误

 

WebBrowser控件有一个ScriptErrorSuppressed属性,将这个属性设置为True时,该控件确实会比原来多做了一点事情,它不仅禁用了脚本出错的对话框,而且还禁用了登陆到需要用户证书的安全站点时出现的登陆对话框。但是如果我们仍然需要这个功能,或者我们想获得脚本出错的通知,或者我们想知道全部的脚本出错的细节时该怎么办呢?

 

脚本错误可以在HtmlWindow.Error事件中捕获,这个事件会在脚本发生错误时触发并包含全部的错误细节信息,但是难点在于HtmlWindow是需要通过HtmlDocument对象才能访问,而该对象并不是什么时候都有效,HtmlDocument对象只在Navigated事件触发时才有效,而如果用户是按F5键刷新浏览器时呢,抱歉,Navigated事件是不会触发的。在经过了很多的尝试后,我发现唯一可行的方法是使用并不是默认WebBrowser控件一部分的DownloadComplete事件。

 

解决方案:

1.       实现DWebBrowserEvents接口

2.       创建一个DownloadComplete事件

3.       DownloadComplete事件触发时,订阅HtmlWindow.Error事件

4.       利用这个Error事件来获得脚本出错的详细信息

5.       设置Handled属性为True来阻止脚本出错

 

过滤弹出窗口

 

弹出窗口大部分情况都是不怎么受欢迎的或者是不适宜的,屏蔽这些弹出窗口需要一些额外的信息。当用户使用Windows XP SP2或者Windows 2003 SP1 或更高版本时,NewWindow3事件可以提供这些辅助信息,如果这个事件没有触发,那么NewWindows2事件会替代该事件。当NewWindow3事件触发时,你可以检查以下内容:

l  是否是用户的操作才导致了新开窗口

l  用户是否按住了覆盖键(Ctrl 键)

l  是否因为当一个窗口正在关闭才导致显示弹出窗口

l  获取将要打开窗口的URL地址

l  更多...

使用NewWindows3事件可以很明显的实现这个目的,如果要使用这个事件,就必须实现DWebBrowserEvents2接口。

 

解决方案:

1.       实现DWebBrowserEvents2接口

2.       创建一个新的事件和一个新的事件参数类

3.       执行这个事件并附带适当的信息

4.       当这个事件触发后,检查这次的导航是否需要取消

 

添加多标签页或多窗口浏览功能

 

多标签页方式浏览在目前似乎变得越来越流行,例如在IE7中,这就是一个新增功能。实现多标签页方式浏览的难点是,你需要在当脚本或者超链接创建一个新窗口的时候去创建相应的新的标签页或子窗口,除此之外,还需要解析出多窗口或者多标签页的窗口名称。(例如:<A href=”http://SomeSite” target=”SomeWindowName”/>)要实现这一点,一些自动化对象(如:NewWindowX事件中的ppDispIWebBrowser2接口中的Application)就需要从新开窗口传回到该事件中。而访问Application属性需要获得IWebBrowser2接口的引用。

 

解决方案:

1.       重载AttachInterfacesDetachInterfaces接口

2.       保存IWebBrowser2接口对象的引用

3.       创建一个Application属性来暴露该接口中的Application属性

4.       实现DWebBrowserEvent2接口

5.       监听NewWindows2/NewWindow3事件

6.       当一个事件触发时,创建一个新的Browser控件的实例

7.       ppDisp事件参数指派给新实例的Application属性               

 

当一个窗口被脚本关闭时需要确认

 

当你在JScript中调用window.close()方法,WebBrowser控件很可能出现假死。因为某种原因,他不能用于导航页面,也不能做其他任何事情。如果我们知道它什么时候发生可能会好一些。当它发生时会触发一系列的事件,但是这些事件没有给我们需要的信息。重载WndProc方法并检测父窗口是否通知该浏览器已经被销毁是唯一可行的解决方法(如果谁知道如何得到WindowsClosing事件来实现这一点是更好的方法)

 

解决方案:

1.       重载WndProc方法

2.       检查WM_PARENTNOTIFY消息

3.       检查WM_DESTRIY参数

4.       如果检测到了上述的内容,则触发一个新的事件(这个事件在例子中称为Quit

 

3、  创建WebBrowser扩展组件

 

从上一节中,我们可以发现上述的所有内容都基本可以归结为两件事:

1.       实现一个IWebBrowser2类型的对象,从中获取Application属性

2.       实现DWebBrowserEvents2接口来触发事件

 

实现IWebBrowser2接口

 

 1  /// <summary>
 2  /// An extended version of the <see cref="WebBrowser"/> control.
 3  /// </summary>

 4  public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser 
 5  {
 6    private UnsafeNativeMethods.IWebBrowser2 axIWebBrowser2;
 7
 8    /// <summary>
 9    /// This method supports the .NET Framework
10    /// infrastructure and is not intended
11    /// to be used directly from your code. 
12    /// Called by the control when the underlying
13    /// ActiveX control is created. 
14    /// </summary>
15    /// <param name="nativeActiveXObject"></param>

16    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
17    protected override void 
18              AttachInterfaces(object nativeActiveXObject)
19    {
20      this.axIWebBrowser2 = 
21        (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject;
22      base.AttachInterfaces(nativeActiveXObject);
23    }

24
25    /// <summary>
26    /// This method supports the .NET Framework infrastructure
27    /// and is not intended to be used directly from your code. 
28    /// Called by the control when the underlying
29    /// ActiveX control is discarded. 
30    /// </summary>

31    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
32    protected override void DetachInterfaces()
33    {
34      this.axIWebBrowser2 = null;
35      base.DetachInterfaces();
36    }

37    
38    
39  }

 

WebBrowser控件有两个尚未公开的接口:AttachInterfaces()DetachInterfaces()。这些方法用于获取IWebBrowser2接口的引用。

 

下一步,我们可以添加Application属性。

 

/// <summary>
/// Returns the automation object for the web browser
/// </summary>

public object Application
{
  
get return axIWebBrowser2.Application; }
}

 

这个属性可以用来创建一个新窗口,并且当创建新窗口事件触发时将浏览器重定向到这个新窗口。

 

实现DWebBrowserEvents2接口

 

在这个例子中实现了下列事件:

l  NewWindow2NewWindow3(用于屏蔽弹出窗口和创建新窗口)

l  DownloadBeginDownloadComplete(用于捕获脚本错误)

l  BeforeNavigate2(用于在导航到一个页面前查看即将导航到的地址)

 

为了简洁的实现DWebBrowserEvents接口,最好的方法是在组件中建立一个私有的嵌入类。这样,所有需要的事件都在一个地方并且容易查找。当我们实例化这个类的时候,我们可以给调用者提供一个引用,利用该引用可以调用方法来触发我们需要的事件。

 

在组件的构造过程中并没有附带这些事件,而是稍微晚一点。这里有两个方法来实现它并且它们是可以重载的。它们是CreateSink()DetachSink()。当我们将这些都添加完以后,我们的代码会像下面这样(注意有些代码为了阅读方便而删掉了)

 

  /// <summary>
  
/// An extended version of the <see cref="WebBrowser"/> control.
  
/// </summary>

  public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
  
{

    
//  (More code here)

    System.Windows.Forms.AxHost.ConnectionPointCookie cookie;
    WebBrowserExtendedEvents events;

    
/// <summary>
    
/// This method will be called to give
    
/// you a chance to create your own event sink
    
/// </summary>

    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    
protected override void CreateSink()
    
{
      
// Make sure to call the base class or the normal events won't fire
      base.CreateSink();
      events 
= new WebBrowserExtendedEvents(this);
      cookie 
= new AxHost.ConnectionPointCookie(this.ActiveXInstance, 
               events, 
typeof(UnsafeNativeMethods.DWebBrowserEvents2));
    }


    
/// <summary>
    
/// Detaches the event sink
    
/// </summary>

    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    
protected override void DetachSink()
    
{
      
if (null != cookie)
      
{
        cookie.Disconnect();
        cookie 
= null;
      }

    }


    
/// <summary>
    
/// Fires when downloading of a document begins
    
/// </summary>

    public event EventHandler Downloading;
    
    
/// <summary>
    
/// Raises the <see cref="Downloading"/> event
    
/// </summary>
    
/// <param name="e">Empty <see cref="EventArgs"/></param>
    
/// <remarks>
    
/// You could start an animation
    
/// or a notification that downloading is starting
    
/// </remarks>

    protected void OnDownloading(EventArgs e)
    
{
      
if (Downloading != null)
        Downloading(
this, e);
    }

    
    
//  (More code here)

    
The Implementation of DWebBrowserEvents2 for firing extra events

 



  }

 

4、  使用这个组件

 

上一节,我们创建了一个新的组件。现在,我们来使用这些新的事件并尽可能多的挖掘浏览器的功能。针对每一个目标,详细的解释如下:

 

捕获脚本错误

 

在示例程序中,有一个工具窗口简单的显示了发生错误的列表并附带了错误的详细内容。一个单一实例类掌握了脚本错误的信息并且当这个信息发生改变时通知所有订阅者,为了捕获这些脚本错误,BrowserControl首先附加到DownloadComplete事件,其次它订阅了HtmlWindow.Error事件。当这个事件触发时,我们注册这个脚本错误并设置Handled属性为True

 

  public partial class BrowserControl : UserControl
  
{
    
public BrowserControl()
    
{
      InitializeComponent();
      _browser 
= new ExtendedWebBrowser();
      _browser.Dock 
= DockStyle.Fill;

      
// Here's the new DownloadComplete event
      _browser.DownloadComplete += 
        
new EventHandler(_browser_DownloadComplete);
      
// Some more code here
      this.containerPanel.Controls.Add(_browser);
      
// Some more code here
    }



    
void _browser_DownloadComplete(object sender, EventArgs e)
    
{
      
// Check wheter the document is available (it should be)
      if (this.WebBrowser.Document != null)
        
// Subscribe to the Error event
        this.WebBrowser.Document.Window.Error += 
          
new HtmlElementErrorEventHandler(Window_Error);
    }


    
void Window_Error(object sender, HtmlElementErrorEventArgs e)
    
{
      
// We got a script error, record it
      ScriptErrorManager.Instance.RegisterScriptError(e.Url, 
                               e.Description, e.LineNumber);
      
// Let the browser know we handled this error.
      e.Handled = true;
    }


    
// Some more code here
  }

 

过滤弹出窗口,并且增加多标签页或多窗口浏览功能

 

捕获弹出窗口必须可以由用户来进行配置。为了示范的目的,我实现了四个级别,从不屏蔽任何窗口到屏蔽所有新窗口。下面的代码是BrowserContorl的一部分,用来展示如何实现这一点。当一个新建窗口被允许后,示例程序展示了如何让新建窗口实现窗口名称的解决方案。

 

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 pressed
  bool 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 site
        if (this.WebBrowser.EncryptionLevel != 
                 WebBrowserEncryptionLevel.Insecure)
          allowPopup 
= true;
        
else
          
// Not a secure site, handle this like the medium filter
          goto case PopupBlockerFilterLevel.Medium;
        
break;
      
case PopupBlockerFilterLevel.Medium:
        
// This is the most dificult one.
        
// Only when the user first inited
        
// and the new window is user inited
        if ((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 tab
    if (!((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;
}

 

这个事件称为StartNewWindow的原因是编码设计规则不允许一个事件的名称以“Before”或者“After”开头。“NewWindowing”事件并没有在这一范围内。

 

使用Quit事件

 

Quit事件触发时,我们只需要找到正确的窗口或者标签页将其关闭,并且”Dispose”这个示例即可。

 

posted on 2008-07-19 23:50  reinstallsys  阅读(2099)  评论(0编辑  收藏  举报