I have come across situations where I have to tackle with alert windows coming up on to my screen randomly i.e. when I am not sure of their occurring behavior. Thus, in this article, our major focus would remain on “How to close an alert window”.

Lately, while developing a test script, I came across a situation where a certain line of a code called a .js file which resulted into a pop up. The pop had both “OK” and “Cancel” button. But the trouble was that by default sometimes Ok is was and the other times Cancel was selected and hence I wasn’t able to handle the alert using WebDriver’s very own switchTo() method. Moreover the pop up came only sometimes and the other times the code ran successfully.

You can face such situations anytime.

I created a work around to deal with such situation. My workaround was to close the alert window whenever it appears. I used one of a java utility to do so. Thus with the help of Robot class, I closed the alert window by pressing the keyword keys.

Robot class is a java based utility which simulates the keyboard and mouse interactions.

The shortcut to close any opened window is: “Alt + Space +C” – Closes the focused window.

Work Around

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class CloseAlert {
// creating WebDriver instance
WebDriver driver;

@Before
public void setUp() throws Exception {
// initializing Webdriver instance
driver = new FirefoxDriver();
// launching application under test
driver.get("https://example.com");
}

@After
public void tearDown() throws Exception {
// quit the browser
driver.quit();
}

@Test
public void test() throws AWTException {
// click on a link that may open an alert pop up
driver.findElement(By.linkText("Click Here!!!"));

// filling the form - Enter teh name
try{
driver.findElement(By.id("Name")).sendKeys("Shruti");
}
catch (UnhandledAlertException e)
{
// instantiating robot class
Robot rb = new Robot();
// keyPress and keyRelease events for closing the pop up
rb.keyPress(KeyEvent.VK_ALT); 
rb.keyPress(KeyEvent.VK_SPACE);
rb.keyPress(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_SPACE);
rb.keyRelease(KeyEvent.VK_ALT); 
driver.findElement(By.id("Name")).sendKeys("Shruti");
}

// enter the lastname 
driver.findElement(By.id("Lastname")).sendKeys("Shrivastava");

}

}

Thus, the above code will close the generated pop up window if any and would start executing the subsequent test steps.

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *