How to capture Alert message using web browser controler?

Asked

Viewed 2,245 times

4

I am developing a robot using the web browser controler of Asp.Net C#.

In this robot I need to identify some messages that appear in Javascript Alert.

The site that the Robot is manipulating is not mine, so there is no way I can make any change in the structure of it.

So, is there any way to get the content of Alert?

  • You tested my answer?

  • @Diegomoreno I had initially understood that you were only asking about "what to use", so I just quoted Selenium Webdriver and gave no detailed example. Now I updated my reply with more comprehensive details demonstrating how to instantiate the Webdriver, how to navigate to the page that should be accessed by the robot and how to interact with elements, and how to get the text of the Alert message.

  • Thank you very much.

2 answers

3


Perhaps the best alternative for you is to use the Selenium Web Driver

With it you can manipulate the browser and have access to all DOM elements, allowing you to simulate a user browsing the site, and you can also run Javascript commands, access CSS, etc.

Below is a basic example of how to get the text of an Alert using Selenium Webdriver:

using NUnit.Framework;
using OpenQA.Selenium.Firefox;

namespace ExemploSeleniumWebDriver
{
    // A classe robo deve ser uma classe de teste para ser executado automaticamente.
    [TestFixture]
    public class Robo
    {
        // As ações do robô são implementadas como testes unitários.
        [Test]
        public void LeiaMensagemDeAlert()
        {
            // Usei aqui o driver do Firefox, mas poderia ser de qualquer outro browser.
            FirefoxDriver driver = new FirefoxDriver();

            // Navega para a página que criei para simular uma mensagem de alert.
            driver.Navigate().GoToUrl("TesteSeleniumWebDriver.html");

            // Clica no botão.
            driver.FindElementByName("botaoDeAlerta").Click();

            // Obtém o texto do Alert.
            string textoDoAlert = driver.SwitchTo().Alert().Text;

            // Fecha a janela do alert.
            driver.SwitchTo().Alert().Dismiss();

            // Digita a mensagem do alert no campo de texto da tela.
            driver.FindElementById("campoDeTexto").SendKeys("O alert continha o seguinte texto: " + textoDoAlert);
        }
    }
}

Contents of the archive Testeseleniumwebdriver.html:

<html>
<head>
    <title>Exemplo do Selenium Web Driver</title>
</head>
<body>
    <input name="botaoDeAlerta" type="button" value="Mostrar Alert" onclick="alert('Teste de obtenção da mensagem de alerta via C#.')" />

    <br />

    <label>Selenium WebDriver irá preencher essa caixa de texto com o texto do alerta:</label>
    <br />
    <input type="text" id="campoDeTexto" />
</body>
</html>

2

To get the message you will have to perform the following procedures:

1- Insert a script tag into the head of your webbrowser containing a new function implementation window.alert, this implementation should add the Alert string to some html element.

2- Perform the procedure for Alert to be displayed and consequently populate the element with the Alert string.

3-Retrieve the string placed in that widget

First Step

Create tag script that will be inserted

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement tagScript = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement bloqAlert = (IHTMLScriptElement)tagScript.DomElement;

Now we define the string representing the contents of the script tag:

You must implement Alert code here, knowing you will receive the Alert message as argument

bloqAlert.text = "window.alert = function (msgAlert) {
//SE A PÁGINA UTILIZAR JQUERY UM EXEMPLO SERIA
$('#elementoUsadoParaReceberAMensagem').val(msgAlert);
}";

Second Step

Add the script tag created to the document head loaded into your webbrowser

head.AppendChild(scriptEl);

Done this if Alert is invoked on the page your message will go to that html element

Third Step

Recovers the string placed in the element

string mensagemAlert = webBrowser1.Document.GetElementById("elementoUsadoParaReceberAMensagem").GetAttribute("value");

Browser other questions tagged

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