-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpuppeteer-har.js
62 lines (56 loc) · 1.44 KB
/
puppeteer-har.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 fs = require('fs');
const { promisify } = require('util');
const { harFromMessages } = require('chrome-har');
// event types to observe
const observe = [
'Page.loadEventFired',
'Page.domContentEventFired',
'Page.frameStartedLoading',
'Page.frameAttached',
'Page.frameScheduledNavigation',
'Network.requestWillBeSent',
'Network.requestServedFromCache',
'Network.dataReceived',
'Network.responseReceived',
'Network.resourceChangedPriority',
'Network.loadingFinished',
'Network.loadingFailed',
];
class PuppeteerHar {
/**
* @param {object} page
*/
constructor(page) {
this.page = page;
this.mainFrame = this.page.mainFrame();
this.events = [];
}
/**
* @param {{path: string}=} options
* @return {Promise<void>}
*/
async start({ path } = {}) {
this.path = path;
this.client = await this.page.target().createCDPSession();
// Enable tracking of relevent activity:
await this.client.send('Page.enable');
await this.client.send('Network.enable');
observe.forEach((method) => {
this.client.on(method, (params) => {
this.events.push({ method, params });
});
});
}
/**
* @returns {Promise<void|object>}
*/
async stop() {
await this.client.detach();
const har = harFromMessages(this.events);
if (this.path) {
await promisify(fs.writeFile)(this.path, JSON.stringify(har));
}
return har;
}
}
module.exports = PuppeteerHar;