-
Notifications
You must be signed in to change notification settings - Fork 25
/
screenshot.js
47 lines (39 loc) · 1.23 KB
/
screenshot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const puppeteer = require('puppeteer');
let browser;
let page;
/**
* HTTP Cloud Function.
* This function is exported by index.js, and is executed when
* you make an HTTP request to the deployed function's endpoint.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.screenshot = async (req, res) => {
const url = req.query.url;
if (!url) {
return res.send('Please provide URL as GET parameter, for example: <a href="?url=https://example.com">?url=https://example.com</a>');
}
const width = req.query.width ? parseInt(req.query.width, 10) : 1280;
const height = req.query.height ? parseInt(req.query.height, 10) : 800;
if(!browser) {
browser = await puppeteer.launch();
}
if(!page) {
page = await browser.newPage();
}
await page.setViewport({width, height});
try {
await page.goto(url);
} catch(e) {
return res.send('Unable to open page');
}
let imageBuffer
try {
imageBuffer = await page.screenshot();
} catch(e) {
return res.send('Unable to take screenshot');
}
res.set('Content-Type', 'image/png');
return res.send(imageBuffer);
};