Substitute for Watir Attach Method, Better 'Use' Method for Webdriver


Let's not kid ourselves, closing popups with Watir, Selenium, and even Webdriver has always been a pain. Even if the built in methods work 95% of the time, that remaining 5% can take sometimes days to sort out a duck tape fix to that specific popup problem. We have definitely had our fair share of headaches dealing with them. This post is about another popup problem and a work around when the Attach method is just not working.

With Watir and Selenium Webdriver, there is no longer an attach method to attach to existing browsers.

Now, there is a use method which tells Webdriver which browser to “use”. However, I’ve found on Firefox and Chrome, if an action causes the popup to close, you are unable to go back to the original browser by using the “use” command. In other words, if you're not supposed to manually click the popup to close it then it is hard for Watir or selenium Webdriver to get attach to existing browsers.

selenium webdriver unhandle error session has no driver

To get back to the original browser, you should first try to connect to any Webdriver instance. This way, you will not get the “session has no driver” message even though there are available Webdriver browsers. Once the Webdriver instance is substantiated, you can then call the “use” command to switch to the specific browser you want.

Here is our solution. It's logic should be applicable with both Watir and Selenium Webdriver.

def attach_browser(browser, how, url)

  browser.window(how, /#{url}/).use

This method should get you back to your first Watir or Selenium Webdriver instance from the stack.