Protractor Dismiss Alerts If Open

11,160

Solution 1

driver.switchTo().alert().then(
    function (alert) { alert.dismiss(); },
    function (err) { }
);

This worked for me. It'll dismiss the alert if it is there, and do nothing if it isn't.

Change dismiss() for accept() if you want to accept the alert (OK) instead of dismissing (Cancel).

Solution 2

//dismiss "wrong credentials" alert
browser.driver.sleep(2000);

browser.switchTo().alert().accept().then(null, function(e) {
  if (e.code !== webdriver.ErrorCode.NO_SUCH_ALERT) {
  throw e;
  }
});

This worked for me in Protractor 2.0. I am sure there is a better solution that doesn't involve using sleep(). After a couple hours of frustration, though, I was just happy to see something that worked.

Exception handling from: https://code.google.com/p/selenium/wiki/WebDriverJs

Solution 3

As in https://code.google.com/p/selenium/wiki/WebDriverJs, you could try/catch to handle the alert

try {
    driver.switchTo().alert().dismiss();
} catch (NoAlertPresentException ignored) {
}

Solution 4

try to override the javascript method to confirm a dialogue if exist

  window.confirm = function() { return true; }

this solution works for me with capybara and cucumber

Share:
11,160
Sakamoto Kazuma
Author by

Sakamoto Kazuma

I am an Automation Framework Engineer. I work mainly with Java-Selenium stack, but have worked with cucumberjs, protractor, and a few other tools here and there. In my spare time, I work on a number of PHP applications I've been trying to put together for a few years now. Also interested in getting into mobile development soon.

Updated on June 04, 2022

Comments

  • Sakamoto Kazuma
    Sakamoto Kazuma almost 2 years

    I am running with protractor and cucumber. For a number of tests, the outcome is problematic, and will sometimes produce an alert box.

    what I'd like to do is in my beginning method for each test, check to see if there is an alert box, and then close/dismiss it. Then continue. The problem I'm facing is, I can't guarantee that there will always be an alert box, and if there isn't one, I get a NoSuchAlertError: no alert open and the entire script stops.

    Is there any way around this?

    Current code:

    try {
      browser.switchTo().alert().dismiss();
    }catch(err){
    
    }
    
  • DarthOpto
    DarthOpto almost 7 years
    Wow, thank you so much. This worked swimmingly well for me.