Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: unable to inject global variable

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?

like image 917
pbnsilva Avatar asked Jan 02 '23 03:01

pbnsilva


1 Answers

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);
like image 89
pbnsilva Avatar answered Jan 08 '23 03:01

pbnsilva