I want to take a screenshot of a page after I inject some data into it:
(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();
})();
And the simple page I test this on:
<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>
The evaluate does not seem to work, as I get:
[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)
What am I doing wrong?
I was able to find the solution in a separate answer on SO:
Puppeteer: unable to inject global variable
Using:
await page.evaluateOnNewDocument((data) => {
window.TestMe = {};
window.TestMe.data = data;
}, jsonData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With