Question: I'm using Capybara with the Selenium webdriver in my testing suite. I've noticed that when all tests are complete, Selenium closes the browser by binding to `at_exit`. However, this causes an issue for my web application displays a "Are you sure you want to navigate away" dialog `onunload` (Please don't judge. This is an intranet application and the users specifically requested it.). So when the tests are done my Cucumber scenario fails (even though all my steps pass) because there was an unhandled Javascript `confirm` dialog. Is there any way to bind after Selenium tries to close the browser and accept the dialog?

**Update**

I believe I have found the issue with this. It appears that after each test, Capybara resets the browser by clearing all cookies and navigating to about:blank. This is what is causing the `onbeforeunload` dialog to open (not `browser.quit()`). I'm cross posting on the Capybara mailing list to try to get help on this and will post anything I find here.

Answer: 
As I mentioned in the OP update it appears that Capybara navigates to about:blank as the end of each Cucumber scenario. After talking with jnicklas from the Capybara team it appears that the best way to handle this is to implement a Cucumber `after` handler which navigates away before Capybara tries to and handle the alert there.

```
After do
  # after each test navigate away before Capybara tries to so that we can appropriately handle the onbeforeunload dialog
  if @browser
    begin
      @browser.navigate.to("about:blank")
      @browser.switch_to.alert.accept
    rescue Selenium::WebDriver::Error::NoAlertPresentError
      # No alert was present. Don't need to do anything
    end
  end
end

```
Like it was mentioned, calling driver.Quit() should solve the problem, but if the pop-up window is causing an issue that prevents the browser from closing, then eliminate the instance. A simple solution is to wrap your test inside of a using clause. 

```
using (IWebDriver driver = new FirefoxDriver())
{
    //Perform your test
    driver.Quit(); 
}

```