在我向页面注入一些数据之后,我想对页面进行截图:
(async () => {
const browser = await puppeteer.launch({dumpio: true});
const page = await browser.newPage();
await page.evaluate((data) => {
console.log("-> evaluate");
window.TestMe = {};
window.TestMe.data = data;
}, jsonData)
await page.goto(url);
await page.screenshot({
path: 'img.png',
});
await browser.close();
})();
我在下面的简单页面上对此进行了测试:
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="content"></div>
<script>
let hasData = window.TestMe && window.TestMe.data;
if (!hasData) {
console.log("ERROR: No data provided by Puppeteer at window.TestMe.data.");
} else {
document.getElementById("content").innerHTML = JSON.stringify(window.TestMe.data);
}
</script>
</body>
</html>
我得到的评估似乎无效:
[0715/103457.665633:INFO:CONSOLE(2)] "-> evaluate", source: __puppeteer_evaluation_script__ (2)
[0715/103457.698770:INFO:CONSOLE(11)] "ERROR: No data provided by Puppeteer at window.TestMe.data.", source: http://localhost:8989/ (11)
我在做什么错了?
谢谢
答案 0 :(得分:1)
我能够在SO的单独答案中找到解决方案:
Puppeteer: unable to inject global variable
使用:
await page.evaluateOnNewDocument((data) => {
window.TestMe = {};
window.TestMe.data = data;
}, jsonData);