gpt4 book ai didi

javascript - Puppeteer console.log - 如何查看 JSHandle@object 内部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:24:23 25 4
gpt4 key购买 nike

我有一个正在使用 Puppeteer 测试的 React/Redux 应用程序。根据文档,我使用以下代码来显示控制台输出:

page.on('console', msg => {
for(let i = 0; i < msg.args().length; ++i) {
let text = msg.args()[i];
console.log(`${i}: ${text}`);
}
});

但是,当 redux-logger 将对象记录到控制台(prevState、nextState)时,Puppeeter 会在我的控制台输出中显示 JSHandle@object。如何查看此对象中的键和属性?

最佳答案

你可以通过 awaitJSHandle 获取 args

接下来对我来说最好的方法是描述来自浏览器的错误并捕获所需类型的 console 通知:

import { ConsoleMessage, Page, JSHandle } from 'puppeteer';
const chalk = require('chalk');

export const listenPageErrors = async (page: Page) => {
// make args accessible
const describe = (jsHandle) => {
return jsHandle.executionContext().evaluate((obj) => {
// serialize |obj| however you want
return `OBJ: ${typeof obj}, ${obj}`;
}, jsHandle);
}

const colors: any = {
LOG: chalk.grey, // (text: any) => text,
ERR: chalk.red,
WAR: chalk.yellow,
INF: chalk.cyan,
};

// listen to browser console there
page.on('console', async (message: ConsoleMessage) => {
const args = await Promise.all(message.args().map(arg => describe(arg)));
// make ability to paint different console[types]
const type = message.type().substr(0, 3).toUpperCase();
const color = colors[type] || chalk.blue;
let text = '';
for (let i = 0; i < args.length; ++i) {
text += `[${i}] ${args[i]} `;
}
console.log(color(`CONSOLE.${type}: ${message.text()}\n${text} `));
});
}

将它放在 const page = await browser.newPage();page.goto(URL) 之间,它将正常工作

const page = await browser.newPage();
await listenPageErrors(page); // <- like there
page.goto(URL)

关于javascript - Puppeteer console.log - 如何查看 JSHandle@object 内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51676159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com