javascript - 执行上下文被破坏,很可能是因为导航 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
解决方案
推荐阅读
- angular - 角度辅助路由在模块内不起作用
- docker - FFmpeg concat 产生不良视频
- angular - 未捕获的类型错误:无法在 getOriginalError 处读取未定义的属性“ngOriginalError”-当 httpClient 返回字符串时
- twitch - Twitch API:是否可以检索当前观看流媒体的人的设备 ID?
- python-3.x - 标准化 PC 的 KMeans 聚类图
- selenium - Appium Parallel Test Execution 删除一个设备的驱动程序,显示会话已终止或未启动
- c# - FakeItEasy:根据表达式返回不同的对象
- python - 在将对象附加到列表时删除引号
- haskell - 如何检查一个 IO() 是否等价于另一个 IO()?
- python - 日志队列和多处理问题