API route to capture and send page screenshot with Puppeteer and Express JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require('puppeteer') | |
app.get('/api/snapshot', async (req, res) => { | |
if (!req.query.url || !req.query.width || !req.query.height) { | |
res.status(400).send({message: 'Invalid input'}) | |
return | |
} | |
// Create a snapshot and send it back | |
try { | |
const browser = await puppeteer.launch({ headless: true }) | |
const page = await browser.newPage() | |
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36') | |
await page.setViewport({ width: parseInt(req.query.width), height: parseInt(req.query.height) }) | |
await page.goto(req.query.url, {waitUntil: 'networkidle2'}) | |
const buffer = await page.screenshot({type: 'png'}) | |
// Send it back | |
res.setHeader('content-type', 'image/png') | |
res.write(buffer,'binary') | |
res.end(null, 'binary') | |
// Close browser and page | |
await page.close() | |
browser.close() | |
} catch (error) { | |
res.status(500).send({message: 'Failed to create snapshot'}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment