Use browser.on('disconnected')
.
You can use browser.on('disconnected')
to listen for when the browser is closed or crashed, or if the browser.disconnect()
method was called.
Then, you can automatically relaunch the browser, and continue with your program.
The following class will launch the browser, and automatically relaunch the browser whenever the 'disconnected'
event is fired:
class BrowserHandler {
constructor() {
const launch_browser = async () => {
this.browser = false;
this.browser = await puppeteer.launch();
this.browser.on('disconnected', launch_browser);
};
(async () => {
await launch_browser();
})();
}
}
BrowserHandler.browser
will return false
when disconnected.
Additionally, the following function will give you the ability to force your program to wait for the browser to finish launching before continuing any further:
const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
const browser_check = setInterval(() => {
if (browser_handler.browser !== false) {
clearInterval(browser_check);
resolve(true);
}
}, 100);
});
Complete Example:
'use strict';
const puppeteer = require('puppeteer');
/**
* Class: BrowserHandler
* Relaunch Browser when Closed
* Return false when Browser is Disconnected
*/
class BrowserHandler {
constructor() {
const launch_browser = async () => {
this.browser = false;
this.browser = await puppeteer.launch();
this.browser.on('disconnected', launch_browser);
};
(async () => {
await launch_browser();
})();
}
}
/**
* Function: wait_for_browser
* Wait for Browser to Finish Launching
*/
const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
const browser_check = setInterval(() => {
if (browser_handler.browser !== false) {
clearInterval(browser_check);
resolve(true);
}
}, 100 );
});
// Main Program
(async () => {
// Open Browser
const browser_handler = new BrowserHandler;
await wait_for_browser(browser_handler);
// Open New Page
let page = await browser_handler.browser.newPage();
await page.goto('https://www.example.com/');
// Disconnect and Automatically Reconnect Browser
browser_handler.browser.disconnect();
if (browser_handler.browser === false) {
console.log('The browser has been disconnected.');
await wait_for_browser(browser_handler);
}
console.log('The browser has been reconnected.');
// Close and Automatically Reopen Browser
await browser_handler.browser.close();
if (browser_handler.browser === false) {
console.log('The browser has been closed.');
await wait_for_browser(browser_handler);
}
console.log('The browser has been reopened.');
// Force Close Puppeteer
process.exit();
})();
Result:
The browser has been disconnected.
The browser has been reconnected.
The browser has been closed.
The browser has been reopened.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…