Web browser control stops javascript notification from site

I am developing a Windows Forms application in VS 2010 C # using the webbrowser control. My goal is to automate the navigation on this website, but when at some point a javascript pop-up warning appears on the website that will stop the automation until I click OK. I somehow solved the problem by simulating the input when it appeared, but the application must remain focused in order for it to work. My question is, is there a way to kill this custom javascript warning from the site (I don't have access to the side, kill it from the client side) so that it does not appear or in any other way fix this problem? The javascript (messagebox) message that appears is not an error is a javascript warning,which the programmers of this website put there for any reason.

+5
source share
1 answer

You can try to use the event Navigatedand intercept DocumentTextbefore the page loads to remove links alert(...);.

On a page Navigatedon MSDN:

Handle an event Navigatedto receive notifications when a control WebBrowsermoves to a new document. When an event occurs Navigated, a new document starts loading, which means that you can access the downloaded content using the properties Document, DocumentTextand DocumentStream.

Here is the code:

using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Your.App
{
    public class PopupSuppress
    {
        WebBrowser _wb;
        public PopupSupress()
        {
            _wb = new WebBrowser();
            _wb.Navigated += new WebBrowserNavigatedEventHandler(_wb_Navigated);
        }

        void _wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            string alertRegexPattern = "alert\\([\\s\\S]*\\);";
            //make sure to only write to _wb.DocumentText if there is a change.
            //This will prompt a reloading of the page (and another 'Navigated' event) [see MSDN link]
            if(Regex.IsMatch(_wb.DocumentText, alertRegexPattern))
                _wb.DocumentText = Regex.Replace(_wb.DocumentText, alertRegexPattern, string.Empty);
        }
    }
}

Sources / Resources:

0
source

All Articles