How to click the ok of the java script alert via WebBrowser?

0

How can I disable all javascript alerts via the web browser?

When I'm loading the page.

<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<meta charset="UTF-8">
<!-- Latest compiled and minified JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script>
alert('Olá, bem vindo ao ultimo passo');
function nextStep()
{
    setTimeout(function () {
       window.location.href = "entrada.php"; //will redirect to your blog page (an ex: blog.php)
    }, 2000);
}
</script>
    <title></title>
</head>
<body onload="alert('Mas não tanto ao ponto de o botão de Finalizar tarefas não funcionar');alert('Boa sorte ;-)');">
<h1>5 - Injeção de JavaScript</h1>
<h2>Objetivo</h2>
<p>Essa página, como você deve ter percebido tem uma sequencia de Alerts, 
o que necessitamos é que você clique em "OK" nos Alerts ou de um jeito 
para que eles não aparecam mais</p>

                <p style="width:500px;text-align:right;">
                    <input type="submit" id="Submit" name="Submit" value="Finalizar Tarefas" class="btn btn-primary" onclick="nextStep();">
                </p>
                <script>
                alert('A Tarefa aqui consiste em barrar o Javascript');

                </script>
</body></html>

She already shows the alert.

alert('Olá, bem vindo ao ultimo passo'); 

I tried to do it in the form below, but I can not.

webBrowser.Navigate(url);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete && webBrowser.Document == null)
{
    Application.DoEvents();
}

var doc = webBrowser.Document.Window.Open(url, "", "", true);

HtmlElement head = doc.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = doc.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string alertBlocker = "window.alert = function () { }";
element.text = alertBlocker;
head.AppendChild(scriptEl);
head.InvokeMember("click");


Thread.Sleep(2000);

HtmlElement submit = doc.Document.GetElementById("submit");
submit.InvokeMember("click");

What I need is to click on "OK" in the Alerts or in a way so they will not show up any more.

    
asked by anonymous 16.10.2017 / 14:47

2 answers

2

I will put it as another answer, because it is a different solution proposed in the first one.

This way, you can not click on the boxes, but prevent them from appearing:

It was necessary to add the COM reference to Microsoft HTML Object Library , and use the namespace mshtml :

Thecodelookslikethis:

usingmshtml;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceBlockJS{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidForm1_Load(objectsender,EventArgse){webBrowser1.ScriptErrorsSuppressed=true;webBrowser1.Navigate("[url]");
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            InjectAlertBlocker();
        }

        private void InjectAlertBlocker()
        {
            HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
            IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
            string alertBlocker = "window.alert = function () { }";
            element.text = alertBlocker;
            head.AppendChild(scriptEl);
        }

    }
}

Putting in your code, from Stap6(); should look something like this:

    public void Stap6()
    {
        webBrowser1.Navigate("http://indigo.rafson.com.br/05.php");
        webBrowser1.Navigated += (s, e) => {

            HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
            IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
            string alertBlocker = "window.alert = function () { }";
            element.text = alertBlocker;
            head.AppendChild(scriptEl);

        };

        NextStap = StapFinalize;
    }
    
16.10.2017 / 18:30
2

As I said, the message is displayed by the browser, and you will not be able to access it through the html of the document. You need to use OS functions to interact with messages:

using System.Runtime.InteropServices;


    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,        string lpszClass, string lpszWindow);

    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string        lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam,        IntPtr lParam);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);


    public static void ClickOKButton()
    {
        IntPtr hwnd = FindWindow("#32770", "Mensagem da página da web");
        SwitchToThisWindow(hwnd, false);
        hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Button", "OK");
        uint message = 0xf5;
        SendMessage(hwnd, message, IntPtr.Zero, IntPtr.Zero);
    }

Note: The alert message does not appear soon after the page loads, there is a delay time, so I use a timer to delay the execution of the method and ensure that it is executed when the message is already on the screen.

    
16.10.2017 / 16:25