Puppeteer中使用Promise时出现TargetCloseError问题求助
Fix for TargetCloseError in Puppeteer with webAction Function
Key Issues in Original Code
- webAction doesn't await async operations: Puppeteer methods like
page.gotoreturn promises, but yourwebActionfunction calls them without awaiting, causing the promise to resolve immediately. This lets the main script finish and close the browser before Puppeteer actions complete. - Uncaught async errors: The
try/catchblock inwebActioncan't catch errors from async functions because it doesn't wait for them to resolve/reject. - webType doesn't return promises: The
webTypefunction doesn't return the promise frompage.type, so even ifwebActionawaited it, it wouldn't wait for typing to finish.
Corrected utils.js Code
module.exports = { // Updated webAction to handle async functions properly webAction: async function (logger, msg, func, ...args) { let actionMessage, actionLevel; try { // Await the async function to ensure it completes before proceeding await func(...args); actionMessage = msg; actionLevel = 'info'; } catch (error) { actionMessage = `Error while executing ${msg} function.\n---\n${error.message}\n---`; actionLevel = 'error'; } finally { logger.log({ level: actionLevel, message: actionMessage }); } return 'Fulfillment value of Promise'; }, // Updated webType to await the page.type promise webType: async function (page, text, xpath) { await page.type( xpath, text, { delay: getRandomIntInRange(constants.minSpeed, constants.maxSpeed) } ); }, };
Explanation of Changes
- Async webAction: By making
webActionan async function and usingawait func(...args), we ensure each Puppeteer operation completes before the function resolves. This prevents the main script from finishing early and closing the browser prematurely. - Proper error handling: Awaiting the async function allows
try/catchto catch any errors thrown during Puppeteer operations, so your logger will correctly record failures (like the invalid XPath test case). - Async webType: Making
webTypeasync ensures the typing operation finishes beforewebActionmoves on, eliminating race conditions between actions.
Expected Behavior After Fix
- The browser will stay open until all
webActioncalls complete. - Each step (page load, element wait, typing attempt) will execute in sequence as intended.
- The invalid XPath will trigger the catch block, logging the error without immediately crashing the browser.
内容的提问来源于stack exchange,提问作者lapdoggo
相关产品推荐
相关产品推荐

