C#のWebBrowserでポップアップとスクリプトエラーを無効化する方法

WebBrowserコントロールを使用する際、スクリプトエラーが発生するとIEブラウザの左下に黄色いアイコンが表示され、エラーメッセージがポップアップされることがあります。このような挙動はユーザー体験を損なうため、アプリケーションの動作にも影響を与える可能性があります。

1. スクリプトエラーの抑制

COM環境では、SHDocVw.dllを使用してWebBrowserコントロールを実装します。この場合、以下のプロパティを設定することでエラーメッセージを非表示にできます。

webBrowser1.Silent = true;

.NET Frameworkでは、マネージド版のWebBrowserが利用可能ですが、ScriptErrorsSuppressedプロパティも同様にエラーを抑制する機能を提供します。ただし、.NET Framework 2.0以降ではこのプロパティが効果を持たないため、イベントハンドラでの処理が必要です。

// エラーイベントの購読
this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

// エラー処理
void Window_Error(object sender, HtmlElementErrorEventArgs e)
{
    e.Handled = true;
}

2. 複雑なフレーム構造への対応

複数のフレーム構成やネストされたページの場合、上記の方法では完全な対応が難しいため、AxWebBrowserを使用したカスタムクラスを作成します。

using SHDocVw;
using System.Windows.Forms;

class CustomWebBrowser : WebBrowser
{
    private SHDocVw.IWebBrowser2 webBrowser2;

    protected override void AttachInterfaces(object nativeActiveXObject)
    {
        webBrowser2 = (SHDocVw.IWebBrowser2)nativeActiveXObject;
        webBrowser2.Silent = true;
        base.AttachInterfaces(nativeActiveXObject);
    }

    protected override void DetachInterfaces()
    {
        webBrowser2 = null;
        base.DetachInterfaces();
    }
}

3. ポップアップウィンドウの無効化

ポップアップウィンドウを制御するには、ActiveXインスタンスのNavigateComplete2イベントを使用し、JavaScript関数をオーバーライドします。

private void webBrowser_NavigateComplete2(object pDisp, ref object URL)
{
    var document = (SHDocVw.WebBrowser)this.webBrowser1.ActiveXInstance;
    var htmlDocument = document.Document as mshtml.IHTMLDocument2;
    
    htmlDocument.parentWindow.execScript("window.alert=null", "javascript");
    htmlDocument.parentWindow.execScript("window.confirm=null", "javascript");
    htmlDocument.parentWindow.execScript("window.open=null", "javascript");
    htmlDocument.parentWindow.execScript("window.showModalDialog=null", "javascript");
    htmlDocument.parentWindow.execScript("window.close=null", "javascript");
}

4. ダイアログの自動処理

ダイアログボックスの「OK」ボタンを自動でクリックするには、alert関数を置き換えるJavaScriptコードを実行します。

private void Form_Load(object sender, EventArgs e)
{
    this.webBrowser1.Navigate("http://localhost:28512/WebSite2/Default.aspx");
    var wb = this.webBrowser1.ActiveXInstance as SHDocVw.WebBrowser;
    wb.NavigateComplete2 += new SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(WebBrowser_NavigateComplete2);
}

private void WebBrowser_NavigateComplete2(object pDisp, ref object URL)
{
    var document = (this.webBrowser1.ActiveXInstance as SHDocVw.WebBrowser).Document as mshtml.IHTMLDocument2;
    document.parentWindow.execScript("function alert(str){return ''}", "javascript");
}

タグ: WebBrowser C# Windows Forms javascript スクリプトエラー

7月1日 17:56 投稿