1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const os = require('os');
|
17 | const path = require('path');
|
18 | const removeFolder = require('rimraf');
|
19 | const childProcess = require('child_process');
|
20 | const BrowserFetcher = require('./BrowserFetcher');
|
21 | const {Connection} = require('./Connection');
|
22 | const {Browser} = require('./Browser');
|
23 | const readline = require('readline');
|
24 | const fs = require('fs');
|
25 | const {helper, assert, debugError} = require('./helper');
|
26 | const ChromiumRevision = require(path.join(helper.projectRoot(), 'package.json')).puppeteer.chromium_revision;
|
27 | const {TimeoutError} = require('./Errors');
|
28 |
|
29 | const mkdtempAsync = helper.promisify(fs.mkdtemp);
|
30 | const removeFolderAsync = helper.promisify(removeFolder);
|
31 |
|
32 | const CHROME_PROFILE_PATH = path.join(os.tmpdir(), 'puppeteer_dev_profile-');
|
33 |
|
34 | const DEFAULT_ARGS = [
|
35 | '--disable-background-networking',
|
36 | '--disable-background-timer-throttling',
|
37 | '--disable-breakpad',
|
38 | '--disable-client-side-phishing-detection',
|
39 | '--disable-default-apps',
|
40 | '--disable-dev-shm-usage',
|
41 | '--disable-extensions',
|
42 |
|
43 | '--disable-features=site-per-process',
|
44 | '--disable-hang-monitor',
|
45 | '--disable-popup-blocking',
|
46 | '--disable-prompt-on-repost',
|
47 | '--disable-sync',
|
48 | '--disable-translate',
|
49 | '--metrics-recording-only',
|
50 | '--no-first-run',
|
51 | '--safebrowsing-disable-auto-update',
|
52 | '--enable-automation',
|
53 | '--password-store=basic',
|
54 | '--use-mock-keychain',
|
55 | ];
|
56 |
|
57 | class Launcher {
|
58 | |
59 |
|
60 |
|
61 |
|
62 | static async launch(options = {}) {
|
63 | const {
|
64 | ignoreDefaultArgs = false,
|
65 | args = [],
|
66 | dumpio = false,
|
67 | executablePath = null,
|
68 | pipe = false,
|
69 | env = process.env,
|
70 | handleSIGINT = true,
|
71 | handleSIGTERM = true,
|
72 | handleSIGHUP = true,
|
73 | ignoreHTTPSErrors = false,
|
74 | defaultViewport = {width: 800, height: 600},
|
75 | slowMo = 0,
|
76 | timeout = 30000
|
77 | } = options;
|
78 |
|
79 | const chromeArguments = [];
|
80 | if (!ignoreDefaultArgs)
|
81 | chromeArguments.push(...this.defaultArgs(options));
|
82 | else if (Array.isArray(ignoreDefaultArgs))
|
83 | chromeArguments.push(...this.defaultArgs(options).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));
|
84 | else
|
85 | chromeArguments.push(...args);
|
86 |
|
87 | let temporaryUserDataDir = null;
|
88 |
|
89 | if (!chromeArguments.some(argument => argument.startsWith('--remote-debugging-')))
|
90 | chromeArguments.push(pipe ? '--remote-debugging-pipe' : '--remote-debugging-port=0');
|
91 | if (!chromeArguments.some(arg => arg.startsWith('--user-data-dir'))) {
|
92 | temporaryUserDataDir = await mkdtempAsync(CHROME_PROFILE_PATH);
|
93 | chromeArguments.push(`--user-data-dir=${temporaryUserDataDir}`);
|
94 | }
|
95 |
|
96 | let chromeExecutable = executablePath;
|
97 | if (!executablePath) {
|
98 | const browserFetcher = new BrowserFetcher();
|
99 | const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision);
|
100 | assert(revisionInfo.local, `Chromium revision is not downloaded. Run "npm install" or "yarn install"`);
|
101 | chromeExecutable = revisionInfo.executablePath;
|
102 | }
|
103 |
|
104 | const usePipe = chromeArguments.includes('--remote-debugging-pipe');
|
105 | const stdio = usePipe ? ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe'];
|
106 | const chromeProcess = childProcess.spawn(
|
107 | chromeExecutable,
|
108 | chromeArguments,
|
109 | {
|
110 |
|
111 |
|
112 |
|
113 | detached: process.platform !== 'win32',
|
114 | env,
|
115 | stdio
|
116 | }
|
117 | );
|
118 |
|
119 | if (dumpio) {
|
120 | chromeProcess.stderr.pipe(process.stderr);
|
121 | chromeProcess.stdout.pipe(process.stdout);
|
122 | }
|
123 |
|
124 | let chromeClosed = false;
|
125 | const waitForChromeToClose = new Promise((fulfill, reject) => {
|
126 | chromeProcess.once('exit', () => {
|
127 | chromeClosed = true;
|
128 |
|
129 | if (temporaryUserDataDir) {
|
130 | removeFolderAsync(temporaryUserDataDir)
|
131 | .then(() => fulfill())
|
132 | .catch(err => console.error(err));
|
133 | } else {
|
134 | fulfill();
|
135 | }
|
136 | });
|
137 | });
|
138 |
|
139 | const listeners = [ helper.addEventListener(process, 'exit', killChrome) ];
|
140 | if (handleSIGINT)
|
141 | listeners.push(helper.addEventListener(process, 'SIGINT', () => { killChrome(); process.exit(130); }));
|
142 | if (handleSIGTERM)
|
143 | listeners.push(helper.addEventListener(process, 'SIGTERM', gracefullyCloseChrome));
|
144 | if (handleSIGHUP)
|
145 | listeners.push(helper.addEventListener(process, 'SIGHUP', gracefullyCloseChrome));
|
146 |
|
147 | let connection = null;
|
148 | try {
|
149 | if (!usePipe) {
|
150 | const browserWSEndpoint = await waitForWSEndpoint(chromeProcess, timeout);
|
151 | connection = await Connection.createForWebSocket(browserWSEndpoint, slowMo);
|
152 | } else {
|
153 | connection = Connection.createForPipe((chromeProcess.stdio[3]), (chromeProcess.stdio[4]), slowMo);
|
154 | }
|
155 | const browser = await Browser.create(connection, [], ignoreHTTPSErrors, defaultViewport, chromeProcess, gracefullyCloseChrome);
|
156 | await ensureInitialPage(browser);
|
157 | return browser;
|
158 | } catch (e) {
|
159 | killChrome();
|
160 | throw e;
|
161 | }
|
162 |
|
163 | |
164 |
|
165 |
|
166 | async function ensureInitialPage(browser) {
|
167 |
|
168 | if (browser.targets().find(target => target.type() === 'page'))
|
169 | return;
|
170 |
|
171 | let initialPageCallback;
|
172 | const initialPagePromise = new Promise(resolve => initialPageCallback = resolve);
|
173 | const listeners = [helper.addEventListener(browser, 'targetcreated', target => {
|
174 | if (target.type() === 'page')
|
175 | initialPageCallback();
|
176 | })];
|
177 |
|
178 | await initialPagePromise;
|
179 | helper.removeEventListeners(listeners);
|
180 | }
|
181 |
|
182 | |
183 |
|
184 |
|
185 | function gracefullyCloseChrome() {
|
186 | helper.removeEventListeners(listeners);
|
187 | if (temporaryUserDataDir) {
|
188 | killChrome();
|
189 | } else if (connection) {
|
190 |
|
191 | connection.send('Browser.close').catch(error => {
|
192 | debugError(error);
|
193 | killChrome();
|
194 | });
|
195 | }
|
196 | return waitForChromeToClose;
|
197 | }
|
198 |
|
199 |
|
200 | function killChrome() {
|
201 | helper.removeEventListeners(listeners);
|
202 | if (chromeProcess.pid && !chromeProcess.killed && !chromeClosed) {
|
203 |
|
204 | try {
|
205 | if (process.platform === 'win32')
|
206 | childProcess.execSync(`taskkill /pid ${chromeProcess.pid} /T /F`);
|
207 | else
|
208 | process.kill(-chromeProcess.pid, 'SIGKILL');
|
209 | } catch (e) {
|
210 |
|
211 | }
|
212 | }
|
213 |
|
214 | try {
|
215 | removeFolder.sync(temporaryUserDataDir);
|
216 | } catch (e) { }
|
217 | }
|
218 | }
|
219 |
|
220 | |
221 |
|
222 |
|
223 |
|
224 | static defaultArgs(options = {}) {
|
225 | const {
|
226 | devtools = false,
|
227 | headless = !devtools,
|
228 | args = [],
|
229 | userDataDir = null
|
230 | } = options;
|
231 | const chromeArguments = [...DEFAULT_ARGS];
|
232 | if (userDataDir)
|
233 | chromeArguments.push(`--user-data-dir=${userDataDir}`);
|
234 | if (devtools)
|
235 | chromeArguments.push('--auto-open-devtools-for-tabs');
|
236 | if (headless) {
|
237 | chromeArguments.push(
|
238 | '--headless',
|
239 | '--hide-scrollbars',
|
240 | '--mute-audio'
|
241 | );
|
242 | if (os.platform() === 'win32')
|
243 | chromeArguments.push('--disable-gpu');
|
244 | }
|
245 | if (args.every(arg => arg.startsWith('-')))
|
246 | chromeArguments.push('about:blank');
|
247 | chromeArguments.push(...args);
|
248 | return chromeArguments;
|
249 | }
|
250 |
|
251 | |
252 |
|
253 |
|
254 | static executablePath() {
|
255 | const browserFetcher = new BrowserFetcher();
|
256 | const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision);
|
257 | return revisionInfo.executablePath;
|
258 | }
|
259 |
|
260 | |
261 |
|
262 |
|
263 |
|
264 | static async connect(options) {
|
265 | const {
|
266 | browserWSEndpoint,
|
267 | ignoreHTTPSErrors = false,
|
268 | defaultViewport = {width: 800, height: 600},
|
269 | slowMo = 0,
|
270 | } = options;
|
271 | const connection = await Connection.createForWebSocket(browserWSEndpoint, slowMo);
|
272 | const {browserContextIds} = await connection.send('Target.getBrowserContexts');
|
273 | return Browser.create(connection, browserContextIds, ignoreHTTPSErrors, defaultViewport, null, () => connection.send('Browser.close').catch(debugError));
|
274 | }
|
275 | }
|
276 |
|
277 |
|
278 |
|
279 |
|
280 |
|
281 |
|
282 | function waitForWSEndpoint(chromeProcess, timeout) {
|
283 | return new Promise((resolve, reject) => {
|
284 | const rl = readline.createInterface({ input: chromeProcess.stderr });
|
285 | let stderr = '';
|
286 | const listeners = [
|
287 | helper.addEventListener(rl, 'line', onLine),
|
288 | helper.addEventListener(rl, 'close', () => onClose()),
|
289 | helper.addEventListener(chromeProcess, 'exit', () => onClose()),
|
290 | helper.addEventListener(chromeProcess, 'error', error => onClose(error))
|
291 | ];
|
292 | const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;
|
293 |
|
294 | |
295 |
|
296 |
|
297 | function onClose(error) {
|
298 | cleanup();
|
299 | reject(new Error([
|
300 | 'Failed to launch chrome!' + (error ? ' ' + error.message : ''),
|
301 | stderr,
|
302 | '',
|
303 | 'TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md',
|
304 | '',
|
305 | ].join('\n')));
|
306 | }
|
307 |
|
308 | function onTimeout() {
|
309 | cleanup();
|
310 | reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${ChromiumRevision}`));
|
311 | }
|
312 |
|
313 | |
314 |
|
315 |
|
316 | function onLine(line) {
|
317 | stderr += line + '\n';
|
318 | const match = line.match(/^DevTools listening on (ws:\/\/.*)$/);
|
319 | if (!match)
|
320 | return;
|
321 | cleanup();
|
322 | resolve(match[1]);
|
323 | }
|
324 |
|
325 | function cleanup() {
|
326 | if (timeoutId)
|
327 | clearTimeout(timeoutId);
|
328 | helper.removeEventListeners(listeners);
|
329 | }
|
330 | });
|
331 | }
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 |
|
362 | module.exports = Launcher;
|