简体   繁体   中英

Node.js: close browser if its open using Pupeteer

I am doing processing using Puppeteer and I am closing the browser like using browser.close() for example something like this

  const browser = await puppeteer.launch({
    headless: true,
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
  });
  try {
  // more processing
  browser.close();
  // more processing
  } catch(err) {
  console.log(err);
  browser.close();
}

I am using browser.close(); in catch block, but sometimes the browser.close() is already executed in try block when the exception occurs.

I want to know if there is a way to check if browser.open? and issue browser.close() only in that case.

Any help in this would be really great. Thanks.

Take a look about try...catch

You should add finally block and add there browser close:)

The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception.

Edit 1

After understanding that issue is detecting if browser is closed I edit and input solution for that problem puppeteer: how check if browser is still open and working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM