Close JavaScript Popup Window In Selenium WebDriver

When you open a webpage, you may find a lot of popup windows. How to close those popups in selenium automation test script? You can achieve that by using Windows Handlers API in selenium webdriver.

Below is the html code which will popup 2 web page when you use Firefox to load it. Save below html code in file C:\WorkSpace\\Code\src\com\dev2qa\webdriver\TestPopUpWebPageWindow.html

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Close Popup Web Page Example. ---</title>
/*Popup and show yahoo homepage. */"");
/*Popup and show bing homepage. */"");
Two homepage will popup one for and the other for

When you use Firefox to open the above Html page, you should enable Allow popup first if your Firefox prevents popup windows. You can click the Allow pop-ups for file:/// menu item to enable the pop-ups.

Following is the java code that close popups. Three methods need to mention.

WebDriver.getWindowHandle() : This method is used to get current browser handler which can used to close it.

WebDriver.getWindowHandles() : This method is used to get all browser handlers.

WebDriver.switchTo().window(String windowHandler) : This method is used to switch to the web page before close it.

System.out.println("Begin closeAllPopupWindows method.");
 /* First create Firefox driver object. */
 WebDriver ffDriver = new FirefoxDriver();

/* Open the html file which will have 2 popups. */
 /* Sleep 3 seconds to wait for the popup complete. */
 System.out.println("Three web page opened, one is the main browserand the other 2 are popups.");
 /* Get main browser title. */
 String mainWindowTitle = ffDriver.getTitle();
 /* Get main browser window handler, this is a string like "{ec1bd5b1-2d5d-4c4d-b11e-9e4497d76899}" */
 String mainWindowHandler = ffDriver.getWindowHandle();
 /* Get all window handlers include popups. */
 Set<String> allWindowHandlers = ffDriver.getWindowHandles();
 /* Loop in the allWindowHandlers. */
 for (String currWindowHandler : allWindowHandlers) {
 /* If not mainWindowHandler then close it. */
 if (!currWindowHandler.equals(mainWindowHandler)) {
 /* First switch to the popup window. */
 /* Get current web page title first, because can not 
 * get this value after close it.
 * */
 String currWindowTitle = ffDriver.getTitle();
 /* Then quite Firefox browser.*/
 System.out.println("Quit popup, browser title is : " + currWindowTitle);
 /* Switch back to the main Firefox browser first, 
 * otherwise an exception will be thrown. */
 /* Then quit main Firefox browser. */
 System.out.println("Quit main web browser, page title is : " + mainWindowTitle);
 System.out.println("End closeAllPopupWindows method.");

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.