Alertas, prompts e confirmações JavaScript
WebDriver fornece uma API para trabalhar com os três tipos nativos de mensagens pop-up oferecidas pelo JavaScript. Esses pop-ups são estilizados pelo navegador e oferecem personalização limitada.
Alertas
O mais simples deles é referido como um alerta, que mostra um mensagem personalizada e um único botão que dispensa o alerta, rotulado na maioria dos navegadores como OK. Ele também pode ser dispensado na maioria dos navegadores pressionando o botão Fechar, mas isso sempre fará a mesma coisa que o botão OK. Veja um exemplo de alerta .
O WebDriver pode obter o texto do pop-up e aceitar ou dispensar esses alertas.
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AlertsTest extends BaseTest {
    @BeforeEach/examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package dev.selenium.interactions;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AlertsTest extends BaseTest {
    @BeforeEach
    public void createSession() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }
    @AfterEach
    public void endSession() {
        driver.quit();
    }
    @Test
    public void alertInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void alertEmptyInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("empty-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("", alert.getText());
        alert.accept();
    }
    @Test
    public void promptDisplayAndInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt")).click();
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
    }
    @Test
    public void promptDefaultInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt-with-default")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.accept();
    }
    @Test
    public void multiplePromptInputsTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("double-prompt")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert1 = driver.switchTo().alert();
        Assertions.assertEquals("First", alert1.getText());
        alert1.sendKeys("first");
        alert1.accept();
        Alert alert2 = driver.switchTo().alert();
        Assertions.assertEquals("Second", alert2.getText());
        alert2.sendKeys("second");
        alert2.accept();
    }
    @Test
    public void slowAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("slow-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Slow", alert.getText());
        alert.accept();
    }
    @Test
    public void confirmationAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("confirm")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Are you sure?", alert.getText());
        alert.accept();
        Assertions.assertTrue(driver.getCurrentUrl().endsWith("simpleTest.html"));
    }
    @Test
    public void iframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void nestedIframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe1 = driver.findElement(By.name("iframeWithIframe"));
        driver.switchTo().frame(iframe1);
        WebElement iframe2 = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe2);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void testForAlerts() {
        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        assertEquals("Sample Alert", alert.getText());
        alert.accept();
        js.executeScript("confirm('Are you sure?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("Are you sure?", alert.getText());
        alert.dismiss();
        js.executeScript("prompt('What is your name?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("What is your name?", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()/examples/python/tests/interactions/test_alerts.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"
def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"
    driver.quit()
def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"
    driver.quit()
def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss/examples/ruby/spec/interactions/alerts_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Alerts' do
  let(:driver) { start_session }
  before do
    driver.navigate.to 'https://selenium.dev'
  end
  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Type a message
    alert.send_keys('selenium')
    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();/examples/javascript/test/interactions/alert.spec.js
const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");
describe('Interactions - Alerts', function () {
    let driver;
    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });
    after(async () => await driver.quit());
    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });
    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });
    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();
        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()
//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())
//Store the alert text in a variable
val text = alert.getText()
//Press the OK button
alert.accept()
  Confirmação
Uma caixa de confirmação é semelhante a um alerta, exceto que o usuário também pode escolher cancelar a mensagem. Veja uma amostra de confirmação .
Este exemplo também mostra uma abordagem diferente para armazenar um alerta:
        driver.findElement(By.id("slow-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Slow", alert.getText());
        alert.accept();/examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package dev.selenium.interactions;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AlertsTest extends BaseTest {
    @BeforeEach
    public void createSession() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }
    @AfterEach
    public void endSession() {
        driver.quit();
    }
    @Test
    public void alertInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void alertEmptyInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("empty-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("", alert.getText());
        alert.accept();
    }
    @Test
    public void promptDisplayAndInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt")).click();
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
    }
    @Test
    public void promptDefaultInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt-with-default")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.accept();
    }
    @Test
    public void multiplePromptInputsTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("double-prompt")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert1 = driver.switchTo().alert();
        Assertions.assertEquals("First", alert1.getText());
        alert1.sendKeys("first");
        alert1.accept();
        Alert alert2 = driver.switchTo().alert();
        Assertions.assertEquals("Second", alert2.getText());
        alert2.sendKeys("second");
        alert2.accept();
    }
    @Test
    public void slowAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("slow-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Slow", alert.getText());
        alert.accept();
    }
    @Test
    public void confirmationAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("confirm")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Are you sure?", alert.getText());
        alert.accept();
        Assertions.assertTrue(driver.getCurrentUrl().endsWith("simpleTest.html"));
    }
    @Test
    public void iframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void nestedIframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe1 = driver.findElement(By.name("iframeWithIframe"));
        driver.switchTo().frame(iframe1);
        WebElement iframe2 = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe2);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void testForAlerts() {
        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        assertEquals("Sample Alert", alert.getText());
        alert.accept();
        js.executeScript("confirm('Are you sure?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("Are you sure?", alert.getText());
        alert.dismiss();
        js.executeScript("prompt('What is your name?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("What is your name?", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()/examples/python/tests/interactions/test_alerts.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"
def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"
    driver.quit()
def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"
    driver.quit()
def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample confirm")).Click();
//Wait for the alert to be displayed
wait.Until(ExpectedConditions.AlertIsPresent());
//Store the alert in a variable
IAlert alert = driver.SwitchTo().Alert();
//Store the alert in a variable for reuse
string text = alert.Text;
//Press the Cancel button
alert.Dismiss();
      # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss/examples/ruby/spec/interactions/alerts_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Alerts' do
  let(:driver) { start_session }
  before do
    driver.navigate.to 'https://selenium.dev'
  end
  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Type a message
    alert.send_keys('selenium')
    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();/examples/javascript/test/interactions/alert.spec.js
const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");
describe('Interactions - Alerts', function () {
    let driver;
    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });
    after(async () => await driver.quit());
    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });
    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });
    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();
        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()
//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())
//Store the alert in a variable
val alert = driver.switchTo().alert()
//Store the alert in a variable for reuse
val text = alert.text
//Press the Cancel button
alert.dismiss()
  Prompt
Os prompts são semelhantes às caixas de confirmação, exceto que também incluem um texto de entrada. Semelhante a trabalhar com elementos de formulário, você pode usar o sendKeys do WebDriver para preencher uma resposta. Isso substituirá completamente o espaço de texto de exemplo. Pressionar o botão Cancelar não enviará nenhum texto. Veja um exemplo de prompt .
    @Test
    public void promptDisplayAndInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt")).click();
        //Wait for the alert to be displayed and store it in a variable/examples/java/src/test/java/dev/selenium/interactions/AlertsTest.java
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package dev.selenium.interactions;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AlertsTest extends BaseTest {
    @BeforeEach
    public void createSession() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }
    @AfterEach
    public void endSession() {
        driver.quit();
    }
    @Test
    public void alertInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void alertEmptyInformationTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("empty-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("", alert.getText());
        alert.accept();
    }
    @Test
    public void promptDisplayAndInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt")).click();
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
    }
    @Test
    public void promptDefaultInputTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("prompt-with-default")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
        alert.accept();
    }
    @Test
    public void multiplePromptInputsTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("double-prompt")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert1 = driver.switchTo().alert();
        Assertions.assertEquals("First", alert1.getText());
        alert1.sendKeys("first");
        alert1.accept();
        Alert alert2 = driver.switchTo().alert();
        Assertions.assertEquals("Second", alert2.getText());
        alert2.sendKeys("second");
        alert2.accept();
    }
    @Test
    public void slowAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("slow-alert")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Slow", alert.getText());
        alert.accept();
    }
    @Test
    public void confirmationAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        driver.findElement(By.id("confirm")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Are you sure?", alert.getText());
        alert.accept();
        Assertions.assertTrue(driver.getCurrentUrl().endsWith("simpleTest.html"));
    }
    @Test
    public void iframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void nestedIframeAlertTest() {
        driver.get("https://www.selenium.dev/selenium/web/alerts.html#");
        WebElement iframe1 = driver.findElement(By.name("iframeWithIframe"));
        driver.switchTo().frame(iframe1);
        WebElement iframe2 = driver.findElement(By.name("iframeWithAlert"));
        driver.switchTo().frame(iframe2);
        driver.findElement(By.id("alertInFrame")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("framed cheese", alert.getText());
        alert.accept();
    }
    @Test
    public void testForAlerts() {
        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        assertEquals("Sample Alert", alert.getText());
        alert.accept();
        js.executeScript("confirm('Are you sure?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("Are you sure?", alert.getText());
        alert.dismiss();
        js.executeScript("prompt('What is your name?');");
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());
        alert = driver.switchTo().alert();
        assertEquals("What is your name?", alert.getText());
        alert.sendKeys("Selenium");
        alert.accept();
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()/examples/python/tests/interactions/test_alerts.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"
def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"
    driver.quit()
def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"
    driver.quit()
def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)
    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample prompt")).Click();
//Wait for the alert to be displayed and store it in a variable
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
//Type your message
alert.SendKeys("Selenium");
//Press the OK button
alert.Accept();
      # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Type a message
    alert.send_keys('selenium')
    # Press on Ok button
    alert.accept/examples/ruby/spec/interactions/alerts_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Alerts' do
  let(:driver) { start_session }
  before do
    driver.navigate.to 'https://selenium.dev'
  end
  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Get the text of the alert
    alert.text
    # Press on Cancel button
    alert.dismiss
  end
  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'
    # Store the alert reference in a variable
    alert = driver.switch_to.alert
    # Type a message
    alert.send_keys('selenium')
    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();/examples/javascript/test/interactions/alert.spec.js
const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");
describe('Interactions - Alerts', function () {
    let driver;
    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });
    after(async () => await driver.quit());
    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });
    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });
    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();
        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});//Click the link to activate the alert
driver.findElement(By.linkText("See a sample prompt")).click()
//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())
//Type your message
alert.sendKeys("Selenium")
//Press the OK button
alert.accept()
  



