How to click on a browser alert using Ruby and Selenium

image of an alert box
Image of an alert box.

Sometimes an action in Selenium will trigger an alert box to appear.  In this case, you will need to dismiss this alert to continue.  Some alerts like the one shown above have two options, “OK” and “Cancel”.  The following Ruby Selenium code will select “OK”:

begin
  driver.switch_to.alert.accept
rescue Selenium::WebDriver::Error::NoAlertOpenError
  retry
end

Note that this code is using a ‘begin, rescue, end’ block.  This is done in case the driver.switch_to.alert command executes before the alert is displayed.  In this case the command will be retried until it finds and accepts the alert.

Caution: If there is no alert, this code will be stuck in an infinite loop.  If there is a chance an alert may not pop up, use a counter to limit the number of times retry is executed.

There may also be times when you wish to cancel the alert.  The following Ruby Selenium code will select “Cancel”:

begin
  driver.switch_to.alert.dismiss
rescue Selenium::WebDriver::Error::NoAlertOpenError
  retry
end

Finally you may want to read the alert text and choose an action based on the text. The following Ruby Selenium code illustrates this:

begin
  alert = driver.switch_to.alert
  if alert.text == "Hello, World!"
    alert.accept
  else
    alert.dismiss
  end
rescue Selenium::WebDriver::Error::NoAlertOpenError
  retry
end

And that’s how you can get past an alert to continue your Selenium tests!  Please comment if you have any questions or suggestion for improvement!  Thanks for reading!