You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Puppeteer中使用Promise时出现TargetCloseError问题求助

Fix for TargetCloseError in Puppeteer with webAction Function

Key Issues in Original Code

  1. webAction doesn't await async operations: Puppeteer methods like page.goto return promises, but your webAction function calls them without awaiting, causing the promise to resolve immediately. This lets the main script finish and close the browser before Puppeteer actions complete.
  2. Uncaught async errors: The try/catch block in webAction can't catch errors from async functions because it doesn't wait for them to resolve/reject.
  3. webType doesn't return promises: The webType function doesn't return the promise from page.type, so even if webAction awaited 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

  1. Async webAction: By making webAction an async function and using await 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.
  2. Proper error handling: Awaiting the async function allows try/catch to catch any errors thrown during Puppeteer operations, so your logger will correctly record failures (like the invalid XPath test case).
  3. Async webType: Making webType async ensures the typing operation finishes before webAction moves on, eliminating race conditions between actions.

Expected Behavior After Fix

  • The browser will stay open until all webAction calls 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:24:55