selenium: What if user close the browser or webdriver? how can I detect if the browser is closed?
You can perform any action on driver object, if it is throwing UnreachableBrowserException, then there is problem to communicate with the browser.
The most common causes for this exception are:
- The provided server address to RemoteWebDriver is invalid, so the connection could not be established.
- The browser has died mid-test.
And you can call the following method to verify the browser is closed or not.
public boolean isBrowserClosed(WebDriver driver){ boolean isClosed = false; try { driver.getTitle(); } catch(UnreachableBrowserException ubex) { isClosed = true; } return isClosed;}
Let me answer your questions one by one :
What if user close the browser or webdriver
: First of allAutomated Test Execution
shouldn't be interuptted byManual Intervention
. It's against all theBest Practices
. If you forcefully close theWeb Browser
thenWebDriver
will throworg.openqa.selenium.WebDriverException
as follows :Exception in thread "main" org.openqa.selenium.WebDriverException: Process unexpectedly closed with status: 0Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'System info: host: 'foo', ip: 'foo', os.name: 'foo', os.arch: 'foo', os.version: 'foo', java.version: 'foo'Driver info: driver.version: FirefoxDriverremote stacktrace: stack backtrace: 0: 0x47e934 - <no info> 1: 0x47f0a3 - <no info> 2: 0x442649 - <no info> 3: 0x449cc3 - <no info> 4: 0x42a890 - <no info> 5: 0x406f5e - <no info> 6: 0x40cfc9 - <no info> 7: 0x6bef19 - <no info> 8: 0x420756 - <no info> 9: 0x6b96e0 - <no info> 10: 0x7fa0fb01842 - BaseThreadInitThunk
How can I detect if the browser is closed?
: If theAutomation Script
handles properinitiation
andclosure
ofWeb Browser
you don't need to explicitly validate ifBrowser is Closed
or not. Cross checking deadWeb Browser
andWeb Browser
session / chores would be a pure Overhead. So a better practice would be to write Clean CodeRestart the webdriver if there is no browser
: Should be handled by theAutomation Script
throughWebDriver
andWeb Browser
initialization.User close the browser, webdriver is not destroyed
: As youWebDriver
andWeb Browser
was started through youAutomation Script
an user closing theWeb Browser
would be a Malpractice.Web Browser
closure must be handled by the theAutomation Script
.I want restart the webdriver
: Neither you can connect to the previous instance of theWebDriver
nor to the previous instance of theWeb Browser
. You have to reinitialize again as follows :WebDriver driver = new ChromeDriver();
See the discussion
How can I reconnect to the browser opened by webdriver with selenium?
for details.