C# webBrowser控件禁用alert,confirm之類的彈窗解決方案


同樣的代碼,我嘗試了很多次都沒有成功。最后終於成功了,是因為我沒有在正確的事件里面調用這段代碼。

    private void InjectAlertBlocker()
        {
            HtmlElement head = wbNav.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = wbNav.Document.CreateElement("script");
            mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)scriptEl.DomElement;
            string alertBlocker = "window.alert = function () { }";
            element.text = alertBlocker;
            head.AppendChild(scriptEl);
            wbNav.ScriptErrorsSuppressed = true;
        }
//阻止彈出新窗口
        private void wbNav_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
    //必須要在這個事件里面調用才能禁用,之前一直寫在別的事件里面,浪費了2小時。 private void wbNav_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            InjectAlertBlocker();
        }

為了加深印象,特別記錄一下。

BTW,別忘記添加 mshtml.dll 這個組件。 全稱:microsoft html object library 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM