Search code examples
seleniumrspecsafaricapybarasafaridriver

Capybara Selenium Navigate To URL Hangs With Popup Alert on Safari


At the end of my tests Capybara automatically navigates to "about:blank" in order to set up the next test. Sometimes the application I'm testing will throw a popup alert if the user leaves the page (which is expected). I have some code to handle this:

  begin
    page.driver.browser.navigate.to("about:blank")
    page.driver.browser.switch_to.alert.accept
  rescue Selenium::WebDriver::Error::NoAlertPresentError
    # No alert was present. Don't need to do anything
  end

This works fine on Firefox, Chrome, and IE. But for some reason on Safari the navigate command hangs, I assume because of the popup. Anyone know a workaround for this?


Solution

  • There is no simple workaround for this at this time in any version of Selenium language bindings. It is a known issue the Selenium team is not interested in resolving. Fundamentally, it is due to the architecture of Safari and consequently the architecture of the Safari Driver.

    The JavaScript of the Safari Driver extension does not know about most of the alerts and popups and dialogs that appear as modal Cocoa layer windows. It also cannot interact with them.

    There is a way but it won't be easy and nobody's done it.

    You would need to use Cocoa.

    So you would want to use RubyCocoa in this case. (or PyObjC if you used Python) You would then possibly also want a sidecar app actually written in Objective-C. The trick would be to use the AX (Accessibility API) and a separate process to observe if there is an alert as the front window and poke at its labels and buttons' text as visible to the AX APIs. AX APIs are probably exposed in RubyCocoa via the ScriptingBridge. However, you would need to add your 'app' to the Security preference pane's list of things allowed to control the computer.

    With that, you could detect the window and handle it.

    It could be fairly brittle across web sites, but if built well, you could handle expected conditions.