The documented solution doesn't work.
// this is the documented solution, which doesn't work
driver.switchTo().alert().dismiss().then(null, function(e) {
if (e.code !== webdriver.ErrorCode.NO_SUCH_ALERT) {
throw e;
}
});
It just throws NoSuchAlertError: no alert open
no matter what. This modified method however, works:
driver.switchTo().alert().thenCatch(function (e) {
// 27 maps to bot.ErrorCode.NO_MODAL_DIALOG_OPEN: http://selenium.googlecode.com/git/docs/api/javascript/source/lib/atoms/error.js.src.html#l31
if (e.code !== 27) { throw e; }
})
.then(function (alert) {
if (alert) { return alert.dismiss(); }
});
This tries to switch to an open alert.
If no alert is found, handles the
NoSuchAlertError
exception but throws other errors up (since we don't want to gobble up every error).- If found, then calls
dismiss
to dismiss it. Feel free to callaccept
if you want.
Note: The position of thenCatch
is crucial. This is against reasoning and against their documented control flow, but this is what works as of today.