Dialogs and alerts
A page calls alert(), confirm() or prompt(), the browser shows a native dialog, and
every subsequent WebDriver command fails until something closes it. If the dialog appears when
your test is not expecting it, the failure is an unexpected alert open error several lines
away from the cause.
Recommended approach
All three dialogs are handled through the same object: switch to the alert, then read its text,
accept it, dismiss it, or send keys to it. alert() can only be accepted; confirm() returns
true to the page when accepted and false when dismissed; prompt() additionally accepts typed
text before being accepted.
Treat the dialog like any other asynchronous event and wait for it. The bindings ship an
alertIsPresent expected condition that returns the alert as soon as it exists, which is both
safer and simpler than switching and catching the error.
For dialogs that may appear when no test code is ready to handle them, set the
unhandledPromptBehavior capability when starting the session. dismiss and accept close
the dialog silently; dismiss and notify (the default) and accept and notify close it and
raise an error so you find out; ignore leaves it open for you to handle. Recent drivers close
beforeunload prompts automatically.
With WebDriver BiDi enabled, the browsing context module also emits userPromptOpened and
userPromptClosed events, so a test can react to a dialog the moment it appears rather than
discovering it on the next command.
Switch to an alert, read its text, and close it:
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
Assertions.assertEquals("cheese", 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));
}
@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();
}
}
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.accept()
assert text == "Sample alert"/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() 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);
});
});Type into a prompt before accepting it:
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
Assertions.assertEquals("Enter something", alert.getText());
alert.sendKeys("Selenium");
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));
}
@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();
}
}
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?"/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() 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);
});
});Decide up front what happens to an unexpected dialog:
chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);
//verify the capability object is not null/examples/java/src/test/java/dev/selenium/drivers/OptionsTest.java
package dev.selenium.drivers;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.chrome.ChromeDriver;
public class OptionsTest extends BaseTest {
@Test
public void setPageLoadStrategyNormal() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://selenium.dev");
} finally {
driver.quit();
}
}
@Test
public void setPageLoadStrategyEager() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://selenium.dev");
} finally {
driver.quit();
}
}
@Test
public void setPageLoadStrategyNone() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://selenium.dev");
} finally {
driver.quit();
}
}
@Test
public void setAcceptInsecureCerts() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setAcceptInsecureCerts(true);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://selenium.dev");
} finally {
driver.quit();
}
}
@Test
public void getBrowserName() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
String name = chromeOptions.getBrowserName();
Assertions.assertFalse(name.isEmpty(), "Browser name should not be empty");
}
@Test
public void setBrowserVersion() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
String version = "latest";
chromeOptions.setBrowserVersion(version);
Assertions.assertEquals(version, chromeOptions.getBrowserVersion());
}
@Test
public void setPlatformName() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
String platform = "OS X 10.6";
chromeOptions.setPlatformName(platform);
Assertions.assertEquals(platform, chromeOptions.getPlatformName().toString());
}
@Test
public void setScriptTimeout() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
Duration duration = Duration.of(5, ChronoUnit.SECONDS);
chromeOptions.setScriptTimeout(duration);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
Duration timeout = driver.manage().timeouts().getScriptTimeout();
Assertions.assertEquals(timeout, duration, "The script timeout should be set to 5 seconds.");
} finally {
driver.quit();
}
}
@Test
public void setPageLoadTimeout() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
Duration duration = Duration.of(5, ChronoUnit.SECONDS);
chromeOptions.setPageLoadTimeout(duration);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
Duration timeout = driver.manage().timeouts().getPageLoadTimeout();
Assertions.assertEquals(timeout, duration, "The page load timeout should be set to 5 seconds.");
} finally {
driver.quit();
}
}
@Test
public void setImplicitWaitTimeout() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
Duration duration = Duration.of(5, ChronoUnit.SECONDS);
chromeOptions.setImplicitWaitTimeout(duration);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
Duration timeout = driver.manage().timeouts().getImplicitWaitTimeout();
Assertions.assertEquals(timeout, duration, "The implicit wait timeout should be set to 5 seconds.");
} finally {
driver.quit();
}
}
@Test
public void setUnhandledPromptBehaviour() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);
//verify the capability object is not null
Object capabilityObject = chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);
Assertions.assertNotNull(capabilityObject, "Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");
Assertions.assertEquals(capabilityObject.toString(), UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());
}
@Test
public void setWindowRect() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT, true);
//verify the capability object is not null
Object capabilityObject = chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);
Assertions.assertNotNull(capabilityObject, "Capability SET_WINDOW_RECT should not be null.");
Boolean capability = (Boolean) capabilityObject;
Assertions.assertTrue(capability, "The capability SET_WINDOW_RECT should be set to true.");
}
@Test
public void setStrictFileInteractability() {
ChromeOptions chromeOptions = getDefaultChromeOptions();
chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY, true);
//verify the capability object is not null
Object capabilityObject = chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);
Assertions.assertNotNull(capabilityObject, "Capability STRICT_FILE_INTERACTABILITY should not be null.");
Boolean capability = (Boolean) capabilityObject;
Assertions.assertTrue(capability, "The capability STRICT_FILE_INTERACTABILITY should be set to true.");
}
}
options = get_default_chrome_options()
options.unhandled_prompt_behavior = 'accept'
driver = webdriver.Chrome(options=options)/examples/python/tests/drivers/test_options.py
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType
def test_page_load_strategy_normal():
options = get_default_chrome_options()
options.page_load_strategy = 'normal'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_page_load_strategy_eager():
options = get_default_chrome_options()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_page_load_strategy_none():
options = get_default_chrome_options()
options.page_load_strategy = 'none'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_timeouts_script():
options = get_default_chrome_options()
options.timeouts = { 'script': 5000 }
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_timeouts_page_load():
options = get_default_chrome_options()
options.timeouts = { 'pageLoad': 5000 }
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_timeouts_implicit_wait():
options = get_default_chrome_options()
options.timeouts = { 'implicit': 5000 }
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_unhandled_prompt():
options = get_default_chrome_options()
options.unhandled_prompt_behavior = 'accept'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_set_window_rect():
options = webdriver.FirefoxOptions()
options.set_window_rect = True # Full support in Firefox
driver = webdriver.Firefox(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_strict_file_interactability():
options = get_default_chrome_options()
options.strict_file_interactability = True
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_proxy():
options = get_default_chrome_options()
options.proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy' : 'http.proxy:1234'})
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_set_browser_name():
options = get_default_chrome_options()
assert options.capabilities['browserName'] == 'chrome'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_set_browser_version():
options = get_default_chrome_options()
options.browser_version = 'stable'
assert options.capabilities['browserVersion'] == 'stable'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_platform_name():
options = get_default_chrome_options()
options.platform_name = 'any'
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def test_accept_insecure_certs():
options = get_default_chrome_options()
options.accept_insecure_certs = True
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/")
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
/examples/dotnet/SeleniumDocs/Drivers/OptionsTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Drivers
{
[TestClass]
public class OptionsTest : BaseTest
{
[TestMethod]
public void SetPageLoadStrategyNormal()
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
IWebDriver driver = new ChromeDriver(chromeOptions);
try
{
// Navigate to Url
driver.Navigate().GoToUrl("https://selenium.dev");
}
finally
{
driver.Quit();
}
}
[TestMethod]
public void SetPageLoadStrategyEager()
{
var chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
IWebDriver driver = new ChromeDriver(chromeOptions);
try
{
driver.Navigate().GoToUrl("https://selenium.dev");
}
finally
{
driver.Quit();
}
}
[TestMethod]
public void SetPageLoadStrategyNone()
{
var chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.None;
IWebDriver driver = new ChromeDriver(chromeOptions);
try
{
driver.Navigate().GoToUrl("https://selenium.dev");
}
finally
{
driver.Quit();
}
}
}
} options = Selenium::WebDriver::Options.chrome
options.unhandled_prompt_behavior = :accept/examples/ruby/spec/drivers/options_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Driver Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
it 'page load strategy normal' do
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :normal
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'page load strategy eager' do
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :eager
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'page load strategy none' do
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :none
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets remote capabilities', skip: 'this is example code that will not execute' do
options = Selenium::WebDriver::Options.firefox
options.platform_name = 'Windows 10'
options.browser_version = 'latest'
cloud_options = {}
cloud_options[:build] = my_test_build
cloud_options[:name] = my_test_name
options.add_option('cloud:options', cloud_options)
driver = Selenium::WebDriver.for :remote, capabilities: options
driver.get(url)
driver.quit
end
it 'accepts untrusted certificates' do
options = Selenium::WebDriver::Options.chrome
options.accept_insecure_certs = true
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets unhandled prompt behavior' do
options = Selenium::WebDriver::Options.chrome
options.unhandled_prompt_behavior = :accept
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets window rect' do
options = Selenium::WebDriver::Options.firefox
options.set_window_rect = true
driver = Selenium::WebDriver.for :firefox, options: options
driver.get(url)
driver.quit
end
it 'sets strict file interactability' do
options = Selenium::WebDriver::Options.chrome
options.strict_file_interactability = true
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets the proxy' do
options = Selenium::WebDriver::Options.chrome
options.proxy = Selenium::WebDriver::Proxy.new(http: 'myproxy.com:8080')
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets the implicit timeout' do
options = Selenium::WebDriver::Options.chrome
options.timeouts = {implicit: 1}
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets the page load timeout' do
options = Selenium::WebDriver::Options.chrome
options.timeouts = {page_load: 400_000}
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets the script timeout' do
options = Selenium::WebDriver::Options.chrome
options.timeouts = {script: 40_000}
driver = Selenium::WebDriver.for :chrome, options: options
driver.get(url)
driver.quit
end
it 'sets capabilities in the pre-selenium 4 way', skip: 'this is example code that will not execute' do
caps = Selenium::WebDriver::Remote::Capabilities.firefox
caps[:platform] = 'Windows 10'
caps[:version] = '92'
caps[:build] = my_test_build
caps[:name] = my_test_name
driver = Selenium::WebDriver.for :remote, url: cloud_url, desired_capabilities: caps
driver.get(url)
driver.quit
end
end
end
Common errors
- NoAlertPresentException:
you switched to an alert before it appeared, or the session’s prompt handler already closed it.
Wait for it with
alertIsPresent, and checkunhandledPromptBehavior. - UnhandledAlertException: a dialog opened that nothing handled, and the driver closed it before running your command. Either handle the dialog in the test or change the prompt handler.
Reference
- JavaScript alerts, prompts and confirmations
- unhandledPromptBehavior
- Expected conditions
- BiDi browsing context events



