问题
How can I console.log something inside the page.evaluate, passing it to node and using it during the evaluation of the page?
I actually want to log the progress of the page.evaluate to the console and show some results to the user.
回答1:
**Updated to work with puppeteer v1.4.x
If all you want is to "log the progress of the page.evaluate to the console", then just
const page = await browser.newPage();
page.on('console', consoleObj => console.log(consoleObj.text()));
And use console.log
in page.evaluate
as usual, no more dependencies are required.
Also see this nice tweak to remove multiple annoying warnings from log.
回答2:
The easiest way to get it to work exactly like you'd expect
const page = await browser.newPage();
page.on('console', (log) => console[log._type](log._text));
回答3:
A lot of the answers provided previously no longer work today. Also one thing that can be very annoying on some pages, is the "warning" messages which pollutes the output. One way to fix that is to filter for the type of the message. The following code helps reduce the noise and works with current versions of Puppeteer:
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', consoleMessageObject => function (consoleMessageObject) {
if (consoleMessageObject._type !== 'warning') {
console.debug(consoleMessageObject._text)
}
});
await page.goto('https://google.com');
const result = await page.evaluate(() => {
console.log('Browser scope.');
return 'Normal scope.';
});
console.log(result)
回答4:
Implement the notifyUi
function in this code sample:
const page = await browser.newPage();
page.on('console', (...args) => {
this.notifyUi('[chrome] ' + args[0]);
});
await page.goto(url);
const result = await page.evaluate(() => {
console.log('I am alive');
return Promise.resolve(true);
});
this.notifyUi('Evaluation returned with ' + result);
回答5:
I like @Vaviloff's answer, but you will log the whole ConsoleMessage object when you may just want the text. Thus, I personally use the below:
const EOL = require('os').EOL;
const _page = await browser.newPage();
_page.on('console', _fCleanLog);
function _fCleanLog(ConsoleMessage) {
console.log(ConsoleMessage.text + EOL);
}
回答6:
const page = await browser.newPage();
page.on('console', ConsoleMessage => console.log(ConsoleMessage.text));
来源:https://stackoverflow.com/questions/46198527/puppeteer-log-inside-page-evaluate