Handle Random Popups in Selenium

In this tutorial, you will see how can you manage the unexpected or random popups in Selenium.

Sometimes there may be scenarios, Once you click something it may open the new tab, new window or new popup window.

Now the problem is, How can we handle such scenarios.


Handle Random PopUps in Selenium

Here, we are taking a scenario for such cases. We don’t know once we will click on the Button, the popup will open or not.

Scenario – Open the Application, click on some button. If popup or the new window will open close it and move further else execute in the Test Case in the normal way.


Let’s see how can you handle such scenarios.

Let’s understand the above-written code.

In above Test Class, we have a static method closePopUp() , why it’s static because we can use it anywhere in the application, It’s not limited to the class itself.


In this method first we store the all open window counts in a variable and if more than one window is the present i.e popup or new window it presents then switch to that window and close it; after closing the popup window switch back to the main window.

We can use this closePopUp() window anywhere in our Test script, Where we have doubt that unexpected pop-up can come at this action.


It will close the unexpected popup window and Test flow will remain.

0 Comment

Leave a Reply