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

Puppeteer使用Network.requestWillBeSent无法捕获JS setTimeout跳转如何解决?

解决方案

核心问题原因

  • 你的代码仅执行了1次page.waitForNavigation(),只能捕获到首次跳转(对应你场景中的第2步301重定向),第3步的JS延时跳转触发前,浏览器就已经被browser.close()关闭,自然无法捕获后续的跳转请求
  • page.waitForNavigation()默认超时时间为30秒,如果你的JS延时跳转超过该时长,会直接抛出超时错误提前终止流程

修改方案

你需要调整等待逻辑,循环监听跳转事件直到没有新跳转产生,同时适配延时跳转的超时配置,修改后代码如下:

const dayjs = require('dayjs');
const AdvancedFormat = require('dayjs/plugin/advancedFormat');
dayjs.extend(AdvancedFormat);

const puppeteer = require('puppeteer');

async function runEmulation () {

  const goToUrl = 'https://example.com/';
  // 最大等待无跳转的时长,单位毫秒,超过这个时间没有新跳转就终止流程
  const MAX_WAIT_TIME = 10000;
  // vars
  const journey = [];
  let lastJumpTime = Date.now();

  // initiate a Puppeteer instance with options and launch
  const browser = await puppeteer.launch({
    headless: false
  });

  // launch a new page
  const page = await browser.newPage();
  // 禁用页面超时
  page.setDefaultNavigationTimeout(0);

  // initiate a new CDP session
  const client = await page.target().createCDPSession();
  await client.send('Network.enable');
  await client.on('Network.requestWillBeSent', async (e) => {

    // if not a document, skip
    if (e.type !== 'Document') return;

    // 避免重复添加同一个URL
    if (journey.some(item => item.url === e.documentURL)) return;

    console.log(`adding URL to journey: ${e.documentURL}`)

    // the journey
    journey.push({
      url: e.documentURL,
      type: e.redirectResponse ? e.redirectResponse.status : 'JS Redirection',
      duration_in_ms: 0,
      duration_in_sec: 0,
      loaded_at: dayjs().valueOf()
    });
    // 每次捕获到新跳转更新最后跳转时间
    lastJumpTime = Date.now();
  });

  await page.goto(goToUrl);
  // 循环等待跳转,直到超过最大无跳转时长
  while (Date.now() - lastJumpTime < MAX_WAIT_TIME) {
    try {
      // 等待跳转,超时设为比最大等待时长小一点,避免卡死
      await page.waitForNavigation({ timeout: MAX_WAIT_TIME / 2 });
    } catch (e) {
      // 超时说明没有新跳转,继续循环判断
    }
  }
  await browser.close();

  console.log('=== JOURNEY ===')
  console.log(journey)
}

// init
runEmulation()

额外优化说明

  • 新增了跳转去重逻辑,避免同一个URL被多次添加到链路中
  • 禁用了默认导航超时,适配长延时的JS跳转场景
  • 新增循环等待逻辑,会在最后一次跳转之后等待你配置的MAX_WAIT_TIME时长,确认没有新跳转再关闭浏览器,能覆盖所有延时跳转场景
  • 如果你不确定JS延时的最大时长,可以适当调大MAX_WAIT_TIME的数值

内容的提问来源于stack exchange,提问作者Ryan H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 08:27:02