I'm using nodejs and webdriver. Its running an infinite loop until I close the browser (thats the idea). Now the question is how I can detect if I close the browser. This is how I've initialized webdriver:
import webdriver from 'selenium-webdriver';
let browser = new webdriver.Builder().usingServer().withCapabilities({
'browserName': 'chrome',
'reuse_browser': false
}).build();
Any guidance on this subject would be appreciated.
I'm using nodejs and webdriver. Its running an infinite loop until I close the browser (thats the idea). Now the question is how I can detect if I close the browser. This is how I've initialized webdriver:
import webdriver from 'selenium-webdriver';
let browser = new webdriver.Builder().usingServer().withCapabilities({
'browserName': 'chrome',
'reuse_browser': false
}).build();
Any guidance on this subject would be appreciated.
Share Improve this question asked Apr 24, 2016 at 20:36 Jeanluca ScaljeriJeanluca Scaljeri 29.2k66 gold badges235 silver badges382 bronze badges2 Answers
Reset to default 4You can catch the error that will get thrown by the Selenium JavaScript bindings if the browser has been closed:
Error: This driver instance does not have a valid session ID (did you call WebDriver.quit()?) and may no longer be used.
see selenium-webdriver/lib/webdriver/webdriver.js around line 402:
function checkHasNotQuit() {
if (!self.session_) {
throw new error.NoSuchSessionError(
'This driver instance does not have a valid session ID ' +
'(did you call WebDriver.quit()?) and may no longer be ' +
'used.');
}
The "session_" variable on the browser object will be available simply as browser.session_ -- however, due to asynchronicity, it may not accurately show if the browser has closed.
Instead, you can send a dummy interaction with the browser, like driver.getTitle(), then catch the error to check if the browser has closed:
try{
driver.getTitle();
// browser is open
} catch(NoSuchSessionError) {
// browser is closed
}
The try/catch
method doesn't work because the webdriver functions run asynchronously. Instead use .then()/.catch()
.
driver.getCurrentUrl().then(function(link){
//Browser is open
resolve(true);
}).catch(function(){
//Browser was closed
resolve(false)
});
You only need to resolve
if you embed this code in a promise, say, to have an easy-to-call browserExists
function.