This repository has been archived by the owner on Jan 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathPuppeteerConnectionDelegate.js
110 lines (90 loc) · 2.92 KB
/
PuppeteerConnectionDelegate.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
'use strict';
const puppeteer = require('puppeteer'),
{Page} = require('puppeteer/lib/Page'),
{Browser} = require('puppeteer/lib/Browser'),
{ConnectionDelegate} = require('@nesk/rialto'),
Logger = require('@nesk/rialto/src/node-process/Logger'),
ConsoleInterceptor = require('@nesk/rialto/src/node-process/NodeInterceptors/ConsoleInterceptor'),
StandardStreamsInterceptor = require('@nesk/rialto/src/node-process/NodeInterceptors/StandardStreamsInterceptor');
/**
* Handle the requests of a connection to control Puppeteer.
*/
class PuppeteerConnectionDelegate extends ConnectionDelegate
{
/**
* Constructor.
*
* @param {Object} options
*/
constructor(options) {
super(options);
this.browsers = new Set;
this.addSignalEventListeners();
}
/**
* @inheritdoc
*/
async handleInstruction(instruction, responseHandler, errorHandler) {
instruction.setDefaultResource(puppeteer);
let value = null;
try {
value = await instruction.execute();
} catch (error) {
if (instruction.shouldCatchErrors()) {
return errorHandler(error);
}
throw error;
}
if (value instanceof Browser) {
this.browsers.add(value);
}
if (this.options.log_browser_console === true && value instanceof Page) {
value.on('console', this.logConsoleMessage);
}
responseHandler(value);
}
/**
* Log the console message.
*
* @param {ConsoleMessage} consoleMessage
*/
async logConsoleMessage(consoleMessage) {
const type = consoleMessage.type();
if (!ConsoleInterceptor.typeIsSupported(type)) {
return;
}
const level = ConsoleInterceptor.getLevelFromType(type);
const args = await Promise.all(consoleMessage.args().map(arg => arg.jsonValue()));
StandardStreamsInterceptor.startInterceptingStrings(message => {
Logger.log('Browser', level, ConsoleInterceptor.formatMessage(message));
});
ConsoleInterceptor.originalConsole[type](...args);
StandardStreamsInterceptor.stopInterceptingStrings();
}
/**
* Listen for process signal events.
*
* @protected
*/
addSignalEventListeners() {
for (let eventName of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(eventName, () => {
this.closeAllBrowsers();
process.exit();
});
}
}
/**
* Close all the browser instances when the process exits.
*
* Calling this method before exiting Node is mandatory since Puppeteer doesn't seem to handle that properly.
*
* @protected
*/
closeAllBrowsers() {
for (let browser of this.browsers.values()) {
browser.close();
}
}
}
module.exports = PuppeteerConnectionDelegate;