Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I am writing tests for a web App using Selenium web driver and came across a scenario where when I try to close the browser I get a popup saying "Are you sure? The page is asking you to confirm that you want to leave - data entered will be lost." with 2 buttons: Leave Page and Stay on Page

How do I click on those buttons

1 Answer

0 votes
by (62.9k points)

There're at least 3 ways to handle this case.

Refresh the page and then dismiss the dialog if the driver supports it :

driver.refresh();

driver.switchTo().alert().accept();

driver.quit();

Setup the browser oriented driver to avoid the prompt :

// Chrome

ChromeOptions options = new ChromeOptions();

options.addArguments("--disable-popup-blocking");

driver = new ChromeDriver(options);

 

// Firefox

FirefoxOptions options = new FirefoxOptions();

options.addPreference("dom.disable_beforeunload", true)

WebDriver driver = new FirefoxDriver(options)

Add some JavaScript code into the page to escape the prompt:

string JS_DISABLE_UNLOAD_DIALOG = "Object.defineProperty(BeforeUnloadEvent.prototype, 'returnValue', { get:function(){}, set:function(){} });"

((JavascriptExecutor)driver).executeScript(JS_DISABLE_UNLOAD_DIALOG);

driver.quit();

Hope this helps!

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, you should enroll yourself in industry-based Selenium online courses!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...