On a page that does not support downloading images or opening them in new tab, I can use the Chrome Developer (Tools->Network) to right click the image and do "copy image as URI".
Is it possible to do the same with puppeteer?
I tried to use few Node.js modules that are intended to convert an image to its base64 representation but they all seem to download the image and then return base64 representation.
Yes, you can use response.buffer()
to get the buffer of a resource. You can then turn the buffer into a base64-encoded string by using buffer.toString('base64')
.
Code Sample
The following example goes to the google.com
website, waits for the first PNG resource and then prints its base64-encoded image.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const [response] = await Promise.all([
page.waitForResponse(response => response.url().includes('.png')),
page.goto('https://www.google.com/')
]);
const buffer = await response.buffer();
console.log('data:image/png;base64,' + buffer.toString('base64'));
await browser.close();
})();
This code sample waits for a single resource. Alternatively, you could listen to the response
event to download multiple images in the same way.
another solution is:
const base64 = await page.screenshot({ encoding: "base64" })
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