const puppeteer = require('puppeteer');
(async () => {
// Launch a new browser instance
const browser = await puppeteer.launch({ headless: false }); // Set headless to false to see the browser
const page = await browser.newPage();
// URL of the page to load
const url = '.p?skuId=6588232';
// Open the page
await page.goto(url, { waitUntil: 'domcontentloaded' });
// Define the selector for the button you are looking for
const buttonSelector = '.c-button.c-button-primary.c-button-lg.c-button-block.c-button-icon.c-button-icon-leading.add-to-cart-button '; // Replace with your button's selector
// Wait for the button to appear or reload the page
while (true) {
try {
// Try to find the button
await page.waitForSelector(buttonSelector, { visible: true, timeout: 50000 });
console.log('Button found!');
break; // Exit the loop once the button is found
} catch (error) {
console.log('Button not found, reloading the page...');
// Reload the page if the button is not found
await page.reload({ waitUntil: 'domcontentloaded' });
}
}
// Close the browser
await browser.close();
})();
I am trying to reload a webpage until a button is found present on the screen. This code works fine when in debug mode on vscode, but when I try running it using node js it gives me an error.
This is the output when running in node js, the first being my program console output which is expected, but then also a thrown error.
$ node test.js Button not found, reloading the page...
C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\CDPSession.js:67return Promise.reject(new Errors_js_1.TargetCloseError(Protocol error (${method}): Session closed. Most likely the ${this.#targetType} has been closed.));^ TargetCloseError: Protocol error (Page.reload): Session closed. Most likely the page has been closed.at CdpCDPSession.send (C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\CDPSession.js:67:35) at CdpPage.reload (C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\li b\cjs\puppeteer\cdp\Page.js:667:39) at C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\test.js:28:18 at process.processTicksAndRejections (node:internal/process/task_queues:105:5) Node.js v22.13.1