Is it possible to modify an element in the DOM with Puppeteer before creating a screenshot? Is it possible to modify an element in the DOM with Puppeteer before creating a screenshot? linux linux

Is it possible to modify an element in the DOM with Puppeteer before creating a screenshot?


you can do that before screen

 await page.evaluate(() => {    let dom = document.querySelector('#id');    dom.innerHTML = "change to something" });


page.$eval()

You can use page.$eval() to change the innerText of an element before taking a screenshot:

await page.$eval('#example', element => element.innerText = 'Hello, world!');await page.screenshot({  path: 'google.png',});


In addition to the excellent answer above, it is important to note that you can't access variables as you normally would expect in the evaluate function. In other words, this won't work:

 const selector = '#id' await page.evaluate(() => {    let dom = document.querySelector(selector)    dom.innerHTML = "change to something" });

You can solve this problem by passing variables to the evaluate function. For example:

 const selector = '#id' await page.evaluate((s) => {    let dom = document.querySelector(s)    dom.innerHTML = "change to something" }, selector);

In the above example I used s as the parameter, but passed in the value stored in selector. Those could be the same variable name, but I wanted to illustrate that the outer variable is not directly used.

If you need to pass in multiple values, use an array:

 const selector = '#id' const newInnerHTML = "change to something" await page.evaluate(([selector, newInnerHTML]) => {    let dom = document.querySelector(selector)    dom.innerHTML = newInnerHTML }, [selector, newInnerHTML]);