How do I click the java script Alert ok via Webbrowser?

Asked

Viewed 978 times

0

How can I disable all javascript alerts via 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’s already face the Alert.

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

I tried to do it the way down, but I’m not getting it.

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 "OK" on the Alerts or in a way so they don’t appear anymore.

  • What is the context of these 'Steps'? Because it depends on the context for the application, in a simple way you can set a session or cookie stating that the Alerts have already been viewed and use an if to know whether or not they need to be shown again.

  • @Anthraxisbr, I don’t understand... what you’re talking about in context ...

  • Context is what these Alerts are, whether they are even for user interaction, or whether they are just page building information, but I think in any case record that they have already been seen in a cookie or in a session will already solve.

  • are user interaction, they are loaded as soon as the page opens in the browser.

  • if(localStorage.getItem('alert1') === '1'){ //nothing }Else{ Alert('Hello, welcome to the last step'); localStorage.setItem('alert1','1'); }. If you start a session for Alert, save a value and compare in the session if it exists, it will only be displayed again at the end of the session, see this excerpt I put here, replace the code of the first Alert with it, if that’s right I prepare a decent response.

  • the message is shown by the browser...and not on the page, you will need to use OS function to search for the message and click the button. I’ve done it and I’ve got the code, coming home public here

Show 1 more comment

2 answers

2

as I commented, the message is displayed by the browser, and you will not be able to access it by the document html. You need to use operating system 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 warning message does not appear soon after the page is loaded, 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.

  • lpClassName This is not dynamic ? Findwindow("#32770"

  • Do you mean Intptr? The code #32770 does not... It seems to me, is the identification of messages... The title of the window, you can change to which appears in your case, but I believe it is the same too

  • #32770 identifies Windows dialog boxes

  • messages are shown in the browser

  • The messages are shown by the browser... I use this code here, works perfectly, failed to work?

  • did not roll here, continue showing

  • https://stackoverflow.com/questions/9770522/how-to-handle-message-boxes-while-using-webbrowser-in-c

Show 3 more comments

2


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

That 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:

inserir a descrição da imagem aqui

The code went like this:

using mshtml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BlockJS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            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);
        }

    }
}

By putting in your code, 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;
    }
  • guy didn’t roll. I don’t know what I did wrong.

  • show your code

  • https://github.com/MarconcilioSouza/stackoverflow/blob/master/WebBrowser_Indigo/WebBrowser_Indigo/Form1.cs

  • Stap6() is what I’m trying to do

  • you didn’t put the code ...

  • 1

    I managed to solve, I had to apply the two answers to solve the problem.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.