Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

Moved the active pages decreasing into page.close event which is fired once the pages is closed or dies.

Petr Patekc670e3ce90ce
diff --git a/src/puppeteer_pool.js b/src/puppeteer_pool.js
index 071157d6e..c4dd4bc8a 100644
--- a/src/puppeteer_pool.js
+++ b/src/puppeteer_pool.js
@@ -339,13 +339,7 @@ class PuppeteerPool {
});
// This one is done manually in Puppeteerpool.newPage() so that it happens immediately.
// browser.on('targetcreated', () => instance.activePages++);
- browser.on('targetdestroyed', (target) => {
- // The event is also called for service workers and Chromium extensions, which must be ignored!
- const type = target.type();
- if (type !== 'page' && type !== 'other') return;
-
- instance.activePages--;
-
+ browser.on('targetdestroyed', () => {
if (instance.activePages === 0 && this.retiredInstances[id]) {
// Run this with a delay, otherwise page.close() that initiated this 'targetdestroyed' event
// might fail with "Protocol error (Target.closeTarget): Target closed."
@@ -554,18 +548,18 @@ class PuppeteerPool {
* @ignore
*/
_decoratePage(page) {
+ const instance = this.pagesToInstancesMap.get(page);
+
const originalPageClose = page.close;
page.close = async (...args) => {
this.closedPages.add(page);
await originalPageClose.apply(page, args)
.catch((err) => {
- const instance = this.pagesToInstancesMap.get(page);
log.debug('PuppeteerPool: Page.close() failed', { errorMessage: err.message, id: instance.id });
});
const context = page.browserContext();
if (context.isIncognito()) {
await context.close().catch((err) => {
- const instance = this.pagesToInstancesMap.get(page);
log.debug('PuppeteerPool: Context.close() failed', { errorMessage: err.message, id: instance.id });
});
}
@@ -575,6 +569,11 @@ class PuppeteerPool {
log.exception(error, 'PuppeteerPool: Page crashed.');
page.close();
});
+
+ page.once('close', () => {
+ instance.activePages--;
+ });
+
return page;
}