javascript - check with Webdriver if browser is still open - Stack Overflow

I'm using nodejs and webdriver. Its running an infinite loop until I close the browser (thats the

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

You 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744257653a4565477.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信