WebDriver provides an API for working with the three types of native
popup messages offered by JavaScript. These popups are styled by the
browser and offer limited customisation.
Alerts
The simplest of these is referred to as an alert, which shows a
custom message, and a single button which dismisses the alert, labelled
in most browsers as OK. It can also be dismissed in most browsers by
pressing the close button, but this will always do the same thing as
the OK button. See an example alert.
WebDriver can get the text from the popup and accept or dismiss these
alerts.
//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());
// 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.importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=newChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.quit();}}
element=driver.find_element(By.LINK_TEXT,"See an example alert")element.click()wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.accept()
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_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(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See an example alert")).Click();//Wait for the alert to be displayed and store it in a variableIAlertalert=wait.Until(ExpectedConditions.AlertIsPresent());//Store the alert text in a variablestringtext=alert.Text;//Press the OK buttonalert.Accept();
# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismiss
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
const{suite}=require('selenium-webdriver/testing');const{By,Browser,until}=require('selenium-webdriver');constassert=require("node:assert");suite(function(env){describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitenv.builder().build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();// Verify
assert.equal(alertText,"Are you sure?");//dismiss alert
awaitalert.dismiss();});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});},{browsers:[Browser.CHROME]});
//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
valalert=wait.until(ExpectedConditions.alertIsPresent())//Store the alert text in a variable
valtext=alert.getText()//Press the OK button
alert.accept()
Confirm
A confirm box is similar to an alert, except the user can also choose
to cancel the message. See
a sample confirm.
This example also shows a different approach to storing an alert:
// 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.importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=newChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.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(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_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(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See a sample confirm")).Click();//Wait for the alert to be displayedwait.Until(ExpectedConditions.AlertIsPresent());//Store the alert in a variableIAlertalert=driver.SwitchTo().Alert();//Store the alert in a variable for reusestringtext=alert.Text;//Press the Cancel buttonalert.Dismiss();
# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismiss
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
const{suite}=require('selenium-webdriver/testing');const{By,Browser,until}=require('selenium-webdriver');constassert=require("node:assert");suite(function(env){describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitenv.builder().build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();// Verify
assert.equal(alertText,"Are you sure?");//dismiss alert
awaitalert.dismiss();});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});},{browsers:[Browser.CHROME]});
//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
valalert=driver.switchTo().alert()//Store the alert in a variable for reuse
valtext=alert.text//Press the Cancel button
alert.dismiss()
Prompt
Prompts are similar to confirm boxes, except they also include a text
input. Similar to working with form elements, you can use WebDriver’s
send keys to fill in a response. This will completely replace the placeholder
text. Pressing the cancel button will not submit any text.
See a sample prompt.
// 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.importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=newChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.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(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_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(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_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(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See a sample prompt")).Click();//Wait for the alert to be displayed and store it in a variableIAlertalert=wait.Until(ExpectedConditions.AlertIsPresent());//Type your messagealert.SendKeys("Selenium");//Press the OK buttonalert.Accept();
# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.accept
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);
const{suite}=require('selenium-webdriver/testing');const{By,Browser,until}=require('selenium-webdriver');constassert=require("node:assert");suite(function(env){describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitenv.builder().build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();// Verify
assert.equal(alertText,"Are you sure?");//dismiss alert
awaitalert.dismiss();});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});},{browsers:[Browser.CHROME]});
//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
valalert=wait.until(ExpectedConditions.alertIsPresent())//Type your message
alert.sendKeys("Selenium")//Press the OK button
alert.accept()