How to close browser popup in Selenium WebDriver

0 votes
I am automating a web App using selenium web driver and when I want to close the browser I get a popup asking "Are you sure? The page is asking you to confirm that you want to leave - data entered will be lost." It has two buttons: Leave Page and Stay on Page

How to click on this popup button?
May 10, 2018 in Selenium by Martin
• 4,330 points

2 answers to this question.

0 votes

You can do this using the below code: 

( ( JavascriptExecutor ) _driver).executeScript( "window.onbeforeunload = function(e){};" );

answered May 10, 2018 by Meci Matt
• 9,460 points
0 votes
answered Jun 14, 2019 by anonymous
Hey! I tried this. It doesn't work. When I run this, the whole browser is getting closed. I just want to handle the pop-up. Any other solution?

Hey Vasuki, you can simply handle the pop-up by using following code snippet: 

// Accepts (Click on OK) on Alert Pop-up window

Alert alertOK = driver.switchTo().alert();

//Rejects (Click on Cancel) on Alert pop-up window.

Alert alertCancel = driver.switchTo().alert();

Tried with below snippet of code, it is failing. Can you please help me ?


    public void display() throws InterruptedException, AWTException {

        ( ( JavascriptExecutor )driver )

        .executeScript( "window.onbeforeunload = function(e){};" );


Alert alertCancel = driver.switchTo().alert();





@Mahesh, is it throwing any error or simply not executing the code? Also, why are you using javascript executor?

Related Questions In Selenium

0 votes
1 answer

How to open a browser window in full screen using Selenium WebDriver with C#

Simply Use this: driver.Manage().Window.Maximize(); READ MORE

answered Jun 7, 2018 in Selenium by Samarpit
• 5,870 points
0 votes
1 answer
0 votes
1 answer

How to disable infobar in Chrome browser in Selenium Webdriver?

Hi Lerry, you can disable Infobars displayed ...READ MORE

answered Jun 3, 2019 in Selenium by Hardeep
0 votes
0 answers

How to handle browser popup in Selenium using Java?

Generally, we scrap the data from websites ...READ MORE

Jun 7, 2019 in Selenium by Vaishnavi
• 1,180 points
0 votes
1 answer

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,510 points
0 votes
1 answer
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,870 points
0 votes
1 answer

How to use such xpath to find web elements

It's much simpler to use: #MyDiv123 > div.super or ...READ MORE

answered Jun 14, 2018 in Selenium by Samarpit
• 5,870 points
0 votes
5 answers
+9 votes
15 answers

How to automate gmail login process using selenium webdriver in java?

Check the below code: Here is the working ...READ MORE

answered Apr 24, 2018 in Selenium by Vardy
• 2,370 points