-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
screenshot.js
75 lines (59 loc) · 1.73 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import chromium from "@sparticuz/chromium";
import puppeteer from "puppeteer-core";
chromium.setHeadlessMode = true;
chromium.setGraphicsMode = false;
async function screenshot(url, options = {}) {
let { format = "jpeg", viewport = [375, 375], dpr = 1, withJs = true, wait, timeout = 8000 } = options;
// Must be between 500 and 8000
timeout = Math.min(Math.max(timeout, 500), 8000);
const browser = await puppeteer.launch({
executablePath: await chromium.executablePath(),
args: chromium.args,
defaultViewport: {
width: viewport[0],
height: viewport[1],
deviceScaleFactor: parseFloat(dpr),
},
headless: chromium.headless,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
if(!withJs) {
page.setJavaScriptEnabled(false);
}
let response = await Promise.race([
page.goto(url, {
waitUntil: wait || ["load"],
timeout,
}),
new Promise(resolve => {
setTimeout(() => {
resolve(false); // false is expected below
}, Math.max(timeout, 0)); // we need time to execute the window.stop before the top level timeout hits
}),
]);
if(response === false) { // timed out, resolved false
await page.evaluate(() => window.stop());
}
// let statusCode = response.status();
// TODO handle 4xx/5xx status codes better
let screenshotOptions = {
type: format,
encoding: "binary",
fullPage: false,
captureBeyondViewport: false,
clip: {
x: 0,
y: 0,
width: viewport[0],
height: viewport[1],
}
};
if(format === "jpeg") {
screenshotOptions.quality = 80;
}
let output = await page.screenshot(screenshotOptions);
await browser.close();
return output;
}
export default screenshot;