Handling multiple browser windows/popups using selenium

There are situations in which we get browser popups or multiple browser window opens, when we open an URL or click on an element on browser.

popups can be blocked in browser using some browser addons,
but for testing purpose, sometimes we need to allow the popups or multiple windows.

A single instance of selenium web-driver can handle multiple popups and browser windows.
Let’s see how web-driver handles these above mentioned popups or browser windows.


Selenium provides 2 methods getWindowHandle() and getWindowHandles() to deal with the multiple browser windows.

getWindowHandle() -

This method returns the current browser window handle id that the web-driver is currently holding.

getWindowHandles() -

This method returns set of browser window handle ids that are invoked/opened by the web-driver, each browser window is corresponds to one id, so we can loop over the Set and work on each browser and close.

and we use switchTo().window(window_handle_id) to switch to different browser windows of the web-driver.

Below is the code implementation and comments of each line explanation

In the above case, we have 2 browser popups / windows, so we handled as above,

Let’s say we have multiple windows like 2 or more, then you can loop the Set and perform some action in each iteration.

Hope that helps!

Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!

Leave a Reply

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