Selenium WebDriver how to close browser popup
Asked Answered
P

10

39

I am writing tests for a web App using selenium webDriver 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?

Payable answered 28/7, 2011 at 0:9 Comment(0)
P
26
 ( ( JavascriptExecutor ) _driver )
            .executeScript( "window.onbeforeunload = function(e){};" );

solved the issue for me

Payable answered 12/8, 2011 at 2:3 Comment(4)
Do you know solution for ruby on rails?Garay
This just removes the popup binding, it does not click a button.Muss
This only works if the page code uses window.onbeforeunload = .... It doesn't work if the page uses window.addEventListener('beforeunload', ...).Depurate
some web will set window.onbeforeunload = function(e){ ........ } then that not work on this case. We can use timer for set it null againNieshanieto
C
19
IAlert alert = driver.SwitchTo().Alert();

alert.Accept(); //for two buttons, choose the affirmative one
// or
alert.Dismiss(); //to cancel the affirmative decision, i.e., pop up will be dismissed and no action will take place
Carcass answered 13/12, 2011 at 21:36 Comment(1)
if you are using python like me, the method is driver.switch_to.alert.accept() ref. https://mcmap.net/q/409712/-webdriver-switchto-alert-function-failsInn
D
13

You can interact with alerts and the like using the Alert API. Switching to the alert and confirm it would look like this (in Java):

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

This is also explained in the Selenium FAQ.

Duyne answered 26/3, 2012 at 14:51 Comment(0)
B
6
def close_all_popups(driver):
    driver.window_handles
    for h in driver.window_handles[1:]:
        driver.switch_to_window(h)
        driver.close()
    driver.switch_to_window(driver.window_handles[0])
Beitz answered 5/6, 2012 at 10:34 Comment(1)
is this aimed at closing popup browser windows, rather than dismissing javascript alerts? because it doesn't work for the latter...Tiffinytiffy
D
1

Not sure what is the structure of the popup that you have used. Here are a few that may work for you if you have used either of as to popup.

If its an alert. you can try:

driver.SwitchTo().Alert()

If its a window that pops up then:

driver.SwitchTo().Window(<windowname>)

For iFrame:

driver.SwitchTo().Frame("iFrmLinks")

Once you get through either of the three then you can access all its internal elements.

Regards Tahir

Demos answered 5/8, 2011 at 15:15 Comment(2)
How to return to original window from Alert/Window/Frame?Diapositive
Given the text presented by OP, the popup is probably an alert.Rauwolfia
B
1

You might try using keyboard events. So once the window pops up:

Tab onto the "Ok" button.

driver.Keyboard.PressKey(Keys.Tab);

You'll have to play around to see how many tab presses are required.

Then hit space.

driver.Keyboard.PressKey(Keys.Space);

Yeah it's sort of a hack, but WebDriver is still pretty immature.

EDIT: This will work for "real" popups, but as another answerer said, maybe not for weird in-page things. Basically, if you can tab to the close button manually, this method should work.

Bushey answered 5/8, 2011 at 15:48 Comment(0)
S
0

I've got the same problem when i have the form of fields and "done editing" submit button, because when Selenium IDE auto-click the javascript function, that responsible to disable confirmation window (leave page or still on it), it does not take "mouseup" mouse event that mean window.confirm still works and auto-pass test was fails. My solution is override javascript function window.onbeforeunload in this case (no need to ask if we know that we do when we record test in Selenium IDE). You can run override script in the Selnium IDE before click on "Save" (or something like this) button through selenium.runScript - it should simple disable the confirmation window.

    Command: runScript
    Target: {window.onbeforeunload=function(e){};}
Soracco answered 13/8, 2014 at 7:29 Comment(0)
T
0

You need to handle the unexpected alerts using try catch blocks. Put your code in try block and catch the 'UnhandledAlertException'

Example:

try{
     .....
     .....
     code here
}catch(UnhandledAlertException e ){
    driver.switchto().alert().dismiss();
}
Typehigh answered 11/8, 2016 at 10:3 Comment(0)
M
0

Here disable all popup

    Dictionary<string, object> commandParameters = new Dictionary<string, object>
    {
        ["source"] = @"
window.alert = function() {}; 
window.confirm = function() { return true; }; 
window.prompt = function(message, defaultValue) { return null; };
window.onbeforeunload = function(){}; 
window.setInterval(function(){window.onbeforeunload = function(){};},1);

let func_addEventListener = window.addEventListener; 
window.addEventListener = function(type,listener,options){ if(type != 'beforeunload') func_addEventListener(type,listener,options);}"
    };
    chromeDriver.ExecuteCdpCommand("Page.addScriptToEvaluateOnNewDocument", commandParameters);

That setInterval may be delay a bit, make sure you delay a bit before leave page

Minx answered 13/7, 2024 at 10:30 Comment(0)
D
-2

Put one of these before the click event:

selenium.chooseCancelOnNextConfirmation()

selenium.chooseOkOnNextConfirmation()
Dorsad answered 28/7, 2011 at 18:57 Comment(1)
@ethan.thomason: I think Poster wants the answer for WebDriver, not for Selenium RC. So, your answer is not preciseDiapositive

© 2022 - 2025 — McMap. All rights reserved.