-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
62 lines (57 loc) · 1.98 KB
/
index.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
const { join } = require('path');
const fs = require('fs').promises;
const emptyFunction = async() => {};
const defaultAfterWritingNewFile = async(filename) => console.log(`${filename} was written`);
class PuppeteerMassScreenshots {
async init(
page,
outputFolder,
options = {}
) {
const runOptions = {
beforeWritingImageFile: emptyFunction,
afterWritingImageFile: defaultAfterWritingNewFile,
beforeAck: emptyFunction,
afterAck: emptyFunction,
...options
}
this.page = page;
this.outputFolder = outputFolder;
this.client = await this.page.target().createCDPSession();
this.canScreenshot = true;
this.client.on('Page.screencastFrame', async (frameObject) => {
if (this.canScreenshot) {
await runOptions.beforeWritingImageFile();
const filename = await this.writeImageFilename(frameObject.data);
await runOptions.afterWritingImageFile(filename);
try {
await runOptions.beforeAck();
await this.client.send('Page.screencastFrameAck', { sessionId: frameObject.sessionId});
await runOptions.afterAck();
} catch(e) {
this.canScreenshot = false;
}
}
});
}
async writeImageFilename(data) {
const filename = join(this.outputFolder, Date.now().toString() + '.jpg');
await fs.writeFile(filename, data, 'base64');
return filename;
}
async start(options = {}) {
const startOptions = {
format: 'jpeg',
quality: 100,
maxWidth: 1920,
maxHeight: 1080,
everyNthFrame: 1,
...options
};
return this.client.send('Page.startScreencast', startOptions);
}
async stop() {
return this.client.send('Page.stopScreencast');
}
}
module.exports = PuppeteerMassScreenshots;