2017-08-15 01:08:06 +00:00
/ * *
* Copyright 2017 Google Inc . All rights reserved .
*
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* /
2017-08-22 03:12:16 +00:00
const os = require ( 'os' ) ;
2017-08-15 01:08:06 +00:00
const path = require ( 'path' ) ;
2017-10-11 07:55:48 +00:00
const removeFolder = require ( 'rimraf' ) ;
2017-08-15 01:08:06 +00:00
const childProcess = require ( 'child_process' ) ;
2018-02-07 17:31:53 +00:00
const BrowserFetcher = require ( './BrowserFetcher' ) ;
2017-10-10 05:31:40 +00:00
const { Connection } = require ( './Connection' ) ;
2018-05-10 20:26:08 +00:00
const { Browser } = require ( './Browser' ) ;
2017-08-15 01:08:06 +00:00
const readline = require ( 'readline' ) ;
2017-08-22 03:12:16 +00:00
const fs = require ( 'fs' ) ;
2018-05-31 23:53:51 +00:00
const { helper , assert , debugError } = require ( './helper' ) ;
2018-02-07 17:31:53 +00:00
const ChromiumRevision = require ( path . join ( helper . projectRoot ( ) , 'package.json' ) ) . puppeteer . chromium _revision ;
2017-08-15 01:08:06 +00:00
2017-10-11 07:55:48 +00:00
const mkdtempAsync = helper . promisify ( fs . mkdtemp ) ;
const removeFolderAsync = helper . promisify ( removeFolder ) ;
2017-08-22 03:12:16 +00:00
const CHROME _PROFILE _PATH = path . join ( os . tmpdir ( ) , 'puppeteer_dev_profile-' ) ;
2017-08-15 01:08:06 +00:00
const DEFAULT _ARGS = [
'--disable-background-networking' ,
'--disable-background-timer-throttling' ,
2018-06-01 01:17:50 +00:00
'--disable-breakpad' ,
2017-08-15 01:08:06 +00:00
'--disable-client-side-phishing-detection' ,
'--disable-default-apps' ,
2018-04-11 03:05:27 +00:00
'--disable-dev-shm-usage' ,
2017-09-15 02:07:22 +00:00
'--disable-extensions' ,
2018-06-01 22:20:37 +00:00
// TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548
'--disable-features=site-per-process' ,
2017-08-15 01:08:06 +00:00
'--disable-hang-monitor' ,
'--disable-popup-blocking' ,
'--disable-prompt-on-repost' ,
'--disable-sync' ,
2017-09-15 02:07:22 +00:00
'--disable-translate' ,
2017-08-15 01:08:06 +00:00
'--metrics-recording-only' ,
'--no-first-run' ,
'--safebrowsing-disable-auto-update' ,
2017-09-29 22:16:32 +00:00
] ;
const AUTOMATION _ARGS = [
'--enable-automation' ,
'--password-store=basic' ,
2017-08-15 01:08:06 +00:00
'--use-mock-keychain' ,
] ;
class Launcher {
/ * *
2018-04-03 22:05:27 +00:00
* @ param { ! LaunchOptions = } options
2017-08-15 01:08:06 +00:00
* @ return { ! Promise < ! Browser > }
* /
2017-08-22 03:12:16 +00:00
static async launch ( options ) {
2017-09-29 22:16:32 +00:00
options = Object . assign ( { } , options || { } ) ;
2018-05-31 23:53:51 +00:00
assert ( ! options . ignoreDefaultArgs || ! options . appMode , '`appMode` flag cannot be used together with `ignoreDefaultArgs`' ) ;
2017-08-28 19:14:21 +00:00
let temporaryUserDataDir = null ;
2017-12-20 01:51:21 +00:00
const chromeArguments = [ ] ;
if ( ! options . ignoreDefaultArgs )
chromeArguments . push ( ... DEFAULT _ARGS ) ;
2018-02-15 01:51:29 +00:00
if ( options . appMode ) {
2017-09-29 22:16:32 +00:00
options . headless = false ;
2018-04-03 22:05:27 +00:00
options . pipe = true ;
2018-02-15 01:51:29 +00:00
} else if ( ! options . ignoreDefaultArgs ) {
2017-09-29 22:16:32 +00:00
chromeArguments . push ( ... AUTOMATION _ARGS ) ;
2018-02-15 01:51:29 +00:00
}
2017-09-29 22:16:32 +00:00
2018-04-03 22:05:27 +00:00
if ( ! options . ignoreDefaultArgs || ! chromeArguments . some ( argument => argument . startsWith ( '--remote-debugging-' ) ) )
chromeArguments . push ( options . pipe ? '--remote-debugging-pipe' : '--remote-debugging-port=0' ) ;
2017-08-28 21:59:41 +00:00
if ( ! options . args || ! options . args . some ( arg => arg . startsWith ( '--user-data-dir' ) ) ) {
2017-08-28 19:14:21 +00:00
if ( ! options . userDataDir )
2017-10-11 07:55:48 +00:00
temporaryUserDataDir = await mkdtempAsync ( CHROME _PROFILE _PATH ) ;
2017-08-18 06:18:08 +00:00
2017-08-28 19:14:21 +00:00
chromeArguments . push ( ` --user-data-dir= ${ options . userDataDir || temporaryUserDataDir } ` ) ;
}
2017-10-10 00:25:25 +00:00
if ( options . devtools === true ) {
chromeArguments . push ( '--auto-open-devtools-for-tabs' ) ;
options . headless = false ;
}
2017-08-15 01:08:06 +00:00
if ( typeof options . headless !== 'boolean' || options . headless ) {
chromeArguments . push (
2017-08-21 23:32:39 +00:00
'--headless' ,
'--disable-gpu' ,
'--hide-scrollbars' ,
2017-08-18 03:54:16 +00:00
'--mute-audio'
2017-08-15 01:08:06 +00:00
) ;
}
2018-05-26 00:26:40 +00:00
if ( ! options . ignoreDefaultArgs && Array . isArray ( options . args ) && options . args . every ( arg => arg . startsWith ( '-' ) ) )
chromeArguments . push ( 'about:blank' ) ;
2017-08-15 01:08:06 +00:00
let chromeExecutable = options . executablePath ;
if ( typeof chromeExecutable !== 'string' ) {
2018-02-07 17:31:53 +00:00
const browserFetcher = new BrowserFetcher ( ) ;
const revisionInfo = browserFetcher . revisionInfo ( ChromiumRevision ) ;
2018-05-31 23:53:51 +00:00
assert ( revisionInfo . local , ` Chromium revision is not downloaded. Run "npm install" or "yarn install" ` ) ;
2017-08-15 01:08:06 +00:00
chromeExecutable = revisionInfo . executablePath ;
}
if ( Array . isArray ( options . args ) )
chromeArguments . push ( ... options . args ) ;
2017-08-21 22:43:36 +00:00
2018-04-03 22:05:27 +00:00
const usePipe = chromeArguments . includes ( '--remote-debugging-pipe' ) ;
2018-02-23 03:06:13 +00:00
const stdio = [ 'pipe' , 'pipe' , 'pipe' ] ;
2018-04-03 22:05:27 +00:00
if ( usePipe )
2018-02-15 01:51:29 +00:00
stdio . push ( 'pipe' , 'pipe' ) ;
2017-10-05 21:34:35 +00:00
const chromeProcess = childProcess . spawn (
chromeExecutable ,
chromeArguments ,
{
2018-03-15 18:50:16 +00:00
// On non-windows platforms, `detached: false` makes child process a leader of a new
// process group, making it possible to kill child process tree with `.kill(-pid)` command.
// @see https://nodejs.org/api/child_process.html#child_process_options_detached
detached : process . platform !== 'win32' ,
2018-02-15 01:51:29 +00:00
env : options . env || process . env ,
stdio
2017-10-05 21:34:35 +00:00
}
) ;
2017-08-15 01:08:06 +00:00
2018-02-23 03:06:13 +00:00
if ( options . dumpio ) {
chromeProcess . stderr . pipe ( process . stderr ) ;
chromeProcess . stdout . pipe ( process . stdout ) ;
}
2017-10-17 22:35:00 +00:00
let chromeClosed = false ;
2017-10-11 07:55:48 +00:00
const waitForChromeToClose = new Promise ( ( fulfill , reject ) => {
2017-09-14 04:27:14 +00:00
chromeProcess . once ( 'close' , ( ) => {
2017-10-17 22:35:00 +00:00
chromeClosed = true ;
2017-09-14 04:27:14 +00:00
// Cleanup as processes exit.
2017-10-11 07:55:48 +00:00
if ( temporaryUserDataDir ) {
removeFolderAsync ( temporaryUserDataDir )
. then ( ( ) => fulfill ( ) )
. catch ( err => console . error ( err ) ) ;
} else {
fulfill ( ) ;
}
2017-09-14 04:27:14 +00:00
} ) ;
} ) ;
2017-08-23 18:55:33 +00:00
2018-04-09 21:49:02 +00:00
const listeners = [ helper . addEventListener ( process , 'exit' , killChrome ) ] ;
2017-08-21 22:43:36 +00:00
if ( options . handleSIGINT !== false )
2018-04-25 22:29:14 +00:00
listeners . push ( helper . addEventListener ( process , 'SIGINT' , ( ) => { killChrome ( ) ; process . exit ( 130 ) ; } ) ) ;
2017-11-16 22:26:32 +00:00
if ( options . handleSIGTERM !== false )
2018-04-09 21:49:02 +00:00
listeners . push ( helper . addEventListener ( process , 'SIGTERM' , gracefullyCloseChrome ) ) ;
2017-11-17 03:28:32 +00:00
if ( options . handleSIGHUP !== false )
2018-04-09 21:49:02 +00:00
listeners . push ( helper . addEventListener ( process , 'SIGHUP' , gracefullyCloseChrome ) ) ;
2017-10-17 22:35:00 +00:00
/** @type {?Connection} */
let connection = null ;
2017-08-21 22:43:36 +00:00
try {
2017-08-21 23:32:39 +00:00
const connectionDelay = options . slowMo || 0 ;
2018-04-03 22:05:27 +00:00
if ( ! usePipe ) {
2018-02-15 01:51:29 +00:00
const timeout = helper . isNumber ( options . timeout ) ? options . timeout : 30000 ;
const browserWSEndpoint = await waitForWSEndpoint ( chromeProcess , timeout ) ;
connection = await Connection . createForWebSocket ( browserWSEndpoint , connectionDelay ) ;
} else {
connection = Connection . createForPipe ( /** @type {!NodeJS.WritableStream} */ ( chromeProcess . stdio [ 3 ] ) , /** @type {!NodeJS.ReadableStream} */ ( chromeProcess . stdio [ 4 ] ) , connectionDelay ) ;
}
2018-05-17 01:09:59 +00:00
const ignoreHTTPSErrors = ! ! options . ignoreHTTPSErrors ;
const setDefaultViewport = ! options . appMode ;
2018-06-01 20:57:50 +00:00
const browser = await Browser . create ( connection , [ ] , ignoreHTTPSErrors , setDefaultViewport , chromeProcess , gracefullyCloseChrome ) ;
await ensureInitialPage ( browser ) ;
return browser ;
2017-08-21 22:43:36 +00:00
} catch ( e ) {
2018-04-09 21:49:02 +00:00
killChrome ( ) ;
2017-08-21 22:43:36 +00:00
throw e ;
2017-08-15 01:08:06 +00:00
}
2018-06-01 20:57:50 +00:00
/ * *
* @ param { ! Browser } browser
* /
async function ensureInitialPage ( browser ) {
// Wait for initial page target to be created.
if ( browser . targets ( ) . find ( target => target . type ( ) === 'page' ) )
return ;
let initialPageCallback ;
const initialPagePromise = new Promise ( resolve => initialPageCallback = resolve ) ;
const listeners = [ helper . addEventListener ( browser , 'targetcreated' , target => {
if ( target . type ( ) === 'page' )
initialPageCallback ( ) ;
} ) ] ;
await initialPagePromise ;
helper . removeEventListeners ( listeners ) ;
}
2017-09-14 04:27:14 +00:00
/ * *
* @ return { Promise }
* /
2018-04-09 21:49:02 +00:00
function gracefullyCloseChrome ( ) {
2017-08-30 05:49:50 +00:00
helper . removeEventListeners ( listeners ) ;
2017-10-17 22:35:00 +00:00
if ( temporaryUserDataDir ) {
2018-04-09 21:49:02 +00:00
killChrome ( ) ;
2017-10-17 22:35:00 +00:00
} else if ( connection ) {
// Attempt to close chrome gracefully
2018-04-09 21:49:02 +00:00
connection . send ( 'Browser.close' ) . catch ( error => {
debugError ( error ) ;
killChrome ( ) ;
} ) ;
2017-09-14 04:27:14 +00:00
}
return waitForChromeToClose ;
2017-08-21 22:43:36 +00:00
}
2017-10-24 23:05:12 +00:00
2018-04-09 21:49:02 +00:00
// This method has to be sync to be used as 'exit' event handler.
function killChrome ( ) {
2017-10-24 23:05:12 +00:00
helper . removeEventListeners ( listeners ) ;
if ( chromeProcess . pid && ! chromeProcess . killed && ! chromeClosed ) {
// Force kill chrome.
2018-03-16 00:40:24 +00:00
try {
if ( process . platform === 'win32' )
childProcess . execSync ( ` taskkill /pid ${ chromeProcess . pid } /T /F ` ) ;
else
process . kill ( - chromeProcess . pid , 'SIGKILL' ) ;
} catch ( e ) {
// the process might have already stopped
}
2017-10-24 23:05:12 +00:00
}
// Attempt to remove temporary profile directory to avoid littering.
try {
removeFolder . sync ( temporaryUserDataDir ) ;
} catch ( e ) { }
}
2017-08-15 01:08:06 +00:00
}
2017-08-15 21:29:42 +00:00
2017-12-20 01:51:21 +00:00
/ * *
* @ return { ! Array < string > }
* /
static defaultArgs ( ) {
return DEFAULT _ARGS . concat ( AUTOMATION _ARGS ) ;
}
2017-09-14 00:39:18 +00:00
/ * *
* @ return { string }
* /
static executablePath ( ) {
2018-02-07 17:31:53 +00:00
const browserFetcher = new BrowserFetcher ( ) ;
const revisionInfo = browserFetcher . revisionInfo ( ChromiumRevision ) ;
2017-09-14 00:39:18 +00:00
return revisionInfo . executablePath ;
}
2017-08-15 21:29:42 +00:00
/ * *
2017-09-29 22:16:32 +00:00
* @ param { ! Object = } options
2017-08-15 21:29:42 +00:00
* @ return { ! Promise < ! Browser > }
* /
2017-09-29 22:16:32 +00:00
static async connect ( options = { } ) {
2018-01-23 00:45:46 +00:00
const connectionDelay = options . slowMo || 0 ;
2018-02-15 01:51:29 +00:00
const connection = await Connection . createForWebSocket ( options . browserWSEndpoint , connectionDelay ) ;
2018-05-10 20:26:08 +00:00
const { browserContextIds } = await connection . send ( 'Target.getBrowserContexts' ) ;
2018-05-17 01:09:59 +00:00
const ignoreHTTPSErrors = ! ! options . ignoreHTTPSErrors ;
return Browser . create ( connection , browserContextIds , ignoreHTTPSErrors , true /* setDefaultViewport */ , null , ( ) => connection . send ( 'Browser.close' ) . catch ( debugError ) ) ;
2017-08-15 21:29:42 +00:00
}
2017-08-15 01:08:06 +00:00
}
/ * *
2017-10-10 05:31:40 +00:00
* @ param { ! Puppeteer . ChildProcess } chromeProcess
2017-08-21 22:43:36 +00:00
* @ param { number } timeout
2017-08-15 21:29:42 +00:00
* @ return { ! Promise < string > }
2017-08-15 01:08:06 +00:00
* /
2017-08-21 22:43:36 +00:00
function waitForWSEndpoint ( chromeProcess , timeout ) {
return new Promise ( ( resolve , reject ) => {
2017-08-15 01:08:06 +00:00
const rl = readline . createInterface ( { input : chromeProcess . stderr } ) ;
2017-08-21 22:43:36 +00:00
let stderr = '' ;
2017-08-21 23:39:04 +00:00
const listeners = [
2017-08-21 22:43:36 +00:00
helper . addEventListener ( rl , 'line' , onLine ) ,
2017-09-29 19:21:24 +00:00
helper . addEventListener ( rl , 'close' , ( ) => onClose ( ) ) ,
helper . addEventListener ( chromeProcess , 'exit' , ( ) => onClose ( ) ) ,
helper . addEventListener ( chromeProcess , 'error' , error => onClose ( error ) )
2017-08-21 22:43:36 +00:00
] ;
2017-08-21 23:39:04 +00:00
const timeoutId = timeout ? setTimeout ( onTimeout , timeout ) : 0 ;
2017-08-21 22:43:36 +00:00
2017-09-29 19:21:24 +00:00
/ * *
* @ param { ! Error = } error
* /
function onClose ( error ) {
2017-08-21 22:43:36 +00:00
cleanup ( ) ;
reject ( new Error ( [
2017-09-29 19:21:24 +00:00
'Failed to launch chrome!' + ( error ? ' ' + error . message : '' ) ,
2017-08-21 22:43:36 +00:00
stderr ,
'' ,
'TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md' ,
'' ,
] . join ( '\n' ) ) ) ;
}
function onTimeout ( ) {
cleanup ( ) ;
reject ( new Error ( ` Timed out after ${ timeout } ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r ${ ChromiumRevision } ` ) ) ;
}
2017-08-15 01:08:06 +00:00
/ * *
* @ param { string } line
* /
function onLine ( line ) {
2017-08-21 22:43:36 +00:00
stderr += line + '\n' ;
2017-08-15 21:29:42 +00:00
const match = line . match ( /^DevTools listening on (ws:\/\/.*)$/ ) ;
2017-08-15 01:08:06 +00:00
if ( ! match )
return ;
2017-08-21 22:43:36 +00:00
cleanup ( ) ;
resolve ( match [ 1 ] ) ;
}
function cleanup ( ) {
if ( timeoutId )
clearTimeout ( timeoutId ) ;
helper . removeEventListeners ( listeners ) ;
2017-08-15 01:08:06 +00:00
}
} ) ;
}
2018-04-03 22:05:27 +00:00
/ * *
* @ typedef { Object } LaunchOptions
* @ property { boolean = } ignoreHTTPSErrors
* @ property { boolean = } headless
* @ property { string = } executablePath
* @ property { number = } slowMo
* @ property { ! Array < string >= } args
* @ property { boolean = } ignoreDefaultArgs
* @ property { boolean = } handleSIGINT
* @ property { boolean = } handleSIGTERM
* @ property { boolean = } handleSIGHUP
* @ property { number = } timeout
* @ property { boolean = } dumpio
* @ property { string = } userDataDir
* @ property { ! Object < string , string | undefined >= } env
* @ property { boolean = } devtools
* @ property { boolean = } pipe
* @ property { boolean = } appMode
* /
2017-08-15 01:08:06 +00:00
module . exports = Launcher ;