首页 > 解决方案 > 执行上下文被破坏,很可能是因为导航 Puppeteer

问题描述

在我的 Puppeteer Node JS 应用程序中,我需要从浏览器网页读取 localStorage 和 cookie,但由于某种原因,我收到以下错误:

UnhandledPromiseRejectionWarning:错误:执行上下文被破坏,很可能是因为导航。

我的 JS 做错了什么/遗漏了什么:

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

const puppeteer = require('puppeteer');
const { config } = require('./config');
const helpers = require('./helpers');
const logs = require('./logs');

const runEmulation = async (body) => {
  logs.debug('starting emulation');

  // vars
  const argOptions = [], journey = [];

  // sandbox config
  if ((config.puppeteer.run_in_sandbox === 'true')) {
    argOptions.push('--no-sandbox');
  }

  // initiate a Puppeteer instance with options and launch
  const browser = await puppeteer.launch({
    args: argOptions,
    headless: (config.puppeteer.run_in_headless === 'true') ? true : false
  });

  // launch a new page
  const page = await browser.newPage()

  // 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;

    const scrapablePageData = async () => {
      
      function getLocalStorage () {
        const values = [];
        const keys = Object.keys(localStorage);
        let index = keys.length;

        while (index--) {
          values.push({
            key: keys[index],
            value: localStorage.getItem(keys[index])
          });
        }

        return values ? values : [];
      }

      return {
        localStorage: getLocalStorage()
      }

    }

    const scrapable = await page.evaluate(scrapablePageData);
    const cookies = await page.cookies();

    // the data we want to log
    journey.push({
      url: e.documentURL,
      type: e.redirectResponse ? e.redirectResponse.status : 'JS Redirection',
      storage: {
        cookies: cookies ?? [],
        local: scrapable.localStorage ?? []
      },
      duration_in_ms: 0,
      duration_in_sec: 0,
      loaded_at: dayjs().valueOf()
    })
  })

  // set userAgent and go to the URL
  await page.setUserAgent(body.userAgent);
  await page.goto(body.url);
  await page.waitForNavigation();

  console.log(journey)
}

exports.runEmulation = runEmulation

标签: javascriptasync-awaitpuppeteer

解决方案


推荐阅读