14

Before using selenium 2.4.0 I had the following code working:

alert = page.driver.browser.switch_to.alert
if alert.text
  ....
end

Selenium 2.4.0 contains the change "* Raise in switch_to.alert when no alert is present.", so I get a No alert is present (Selenium::WebDriver::Error::NoAlertOpenError) exception.

How can I check for the presence of an alert with selenium-web-driver 2.4.0?

gucki
  • 4,582
  • 7
  • 44
  • 56

5 Answers5

23

Here is one option:

driver.switch_to.alert.accept rescue Selenium::WebDriver::Error::NoAlertOpenError

This will click OK on the alert if one is present, else it will fail gracefully (silently).

Daniel
  • 239
  • 2
  • 3
  • 3
    Unfortunately this is the best way I have to do this with Capybara. But I had to tweak it slightly: page.driver.browser.switch_to.alert.accept rescue Selenium::WebDriver::Error::NoAlertPresentError – jackocnr Jul 19 '13 at 09:51
  • 1
    Thank you guys so much!!! I've spent hours today trying to get my specs to run and this did the trick :) – Rebekah Waterbury Sep 23 '13 at 22:44
  • 1
    This, with @jackocnr's suggestion, should be the accepted answer IMO. – mattsch Feb 09 '17 at 16:46
9

I implemented a method to handle this in Ruby that I think is pretty clean:

def alert_present?
  begin
    session.driver.browser.switch_to.alert
    puts "Alert present! Switched to alert."
    true
  rescue
    puts "No alert present."
    return false
  end
end
aceofbassgreg
  • 3,837
  • 2
  • 32
  • 42
  • I should add: the 'session' here represents a Capybara session, though obviously this would work with just Selenium if you leave the 'session' part off. – aceofbassgreg Mar 27 '14 at 13:52
  • For all selenium users: you can use `driver.switch_to.alert` where `driver` being an `Selenium::WebDriver` object. – dcts Jan 16 '20 at 12:55
8
WebDriverWait wait = new WebDriverWait(driver, 18);
wait.until(ExpectedConditions.alertIsPresent());
Satish
  • 724
  • 3
  • 10
  • 22
1
status = true
while (status)
    alert = driver.switch_to.alert rescue "exception happened"
    if (alert == "exception happened")
        status = true
        alert = "nothing happened"
    else
        status = false
    end
end

There is no direct method to check if alert is there. Using the above method you can check if alert is there. It will come out of the while loop once alert is present

James
  • 5,137
  • 5
  • 40
  • 80
Satheesh
  • 21
  • 1
0

I used

driver.switch_to.alert.accept rescue 
Selenium::WebDriver::Error::NoAlertOpenError

for selenium-webdriver 3.142.3

Reegan Miranda
  • 2,879
  • 6
  • 43
  • 55