How to automate Alert boxes and Pop-ups


Handling alerts

Surely you have encountered a situation when a pop-up jumps out of nowhere and needs to be confirmed or dismissed. Those pop-ups will cause your test to fail if not handled correctly. There is a simple way to handle such situations using driver.switchTo().alert method.

The alert interface provides the below few methods which are widely used in Selenium Webdriver.

  • dismiss() - Click on the ‘Cancel’ button of the alert.
  • accept() - Click on the ‘OK’ button of the alert.
  • getText() - Capture the alert message.
  • sendKeys(String stringToSend) - Send some data to alert box.

In this example, we will use this neat web page to automate a pop-up confirm scenario.

The steps are the following:

  • Locate the button that triggers the pop-up, generate the selector and use .click() method on it.
Java Projects:
TypeScript Projects:
await browser.wait(ExpectedConditions.visibilityOf(element(this.makePopUpButton)), browser.allScriptsTimeout, this.makePopUpButton.toString());
await element(this.makePopUpButton).click(); 
  • After that accept the pop-up using the .switchTo().alert().accept() method
Java Projects:
TypeScript Projects:

The complete Java project code for this step in the Page Object file would look like this:

public PopupPo AcceptPopup() {
        // Click on the button to make a popup

        // Accept the poput
        return this;

That’s about it! Use your method in the actual test and get rid of those alerts!

public void AcceptThePopup() {
        WebDriver driver = getDriver();

        // Instantiate PO file
        PopupPo popupTest = new PopupPo(driver);"");

        // Click the button and accept the popup

Of course, you can use the alert.dismiss() or alert.sendKeys() methods in the same fashion.

Find out more about handling alerts in TypeScript Protractor Projects and here for Java Projects.