From f7b24a022df6da7c9aa9e9a4bcf94eea042f6453 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Fri, 29 Sep 2023 14:47:30 -0700 Subject: [PATCH] add portStrictMode option (#319) Co-authored-by: Paul Irish --- README.md | 7 +++++++ src/chrome-launcher.ts | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/README.md b/README.md index 9bf9b7254..5237d6dae 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,13 @@ npm install chrome-launcher // Default: an available port is autoselected port: number; + // (optional) When `port` is specified *and* no Chrome is found at that port, + // * if `false` (default), chrome-launcher will launch a new Chrome with that port. + // * if `true`, throw an error + // This option is useful when you wish to explicitly connect to a running Chrome, such as on a mobile device via adb + // Default: false + portStrictMode: boolean; + // (optional) Additional flags to pass to Chrome, for example: ['--headless', '--disable-gpu'] // See: https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md // Do note, many flags are set by default: https://github.com/GoogleChrome/chrome-launcher/blob/main/src/flags.ts diff --git a/src/chrome-launcher.ts b/src/chrome-launcher.ts index 7b769b77b..813e8fa58 100644 --- a/src/chrome-launcher.ts +++ b/src/chrome-launcher.ts @@ -33,6 +33,7 @@ export interface Options { chromeFlags?: Array; prefs?: Record; port?: number; + portStrictMode?: boolean; handleSIGINT?: boolean; chromePath?: string; userDataDir?: string|boolean; @@ -119,6 +120,7 @@ class Launcher { private chromeFlags: string[]; private prefs: Record; private requestedPort?: number; + private portStrictMode?: boolean; private connectionPollInterval: number; private maxConnectionRetries: number; private fs: typeof fs; @@ -142,6 +144,7 @@ class Launcher { this.chromeFlags = defaults(this.opts.chromeFlags, []); this.prefs = defaults(this.opts.prefs, {}); this.requestedPort = defaults(this.opts.port, 0); + this.portStrictMode = opts.portStrictMode; this.chromePath = this.opts.chromePath; this.ignoreDefaultFlags = defaults(this.opts.ignoreDefaultFlags, false); this.connectionPollInterval = defaults(this.opts.connectionPollInterval, 500); @@ -263,6 +266,10 @@ class Launcher { `Found existing Chrome already running using port ${this.port}, using that.`); return; } catch (err) { + if (this.portStrictMode) { + throw new Error(`found no Chrome at port ${this.requestedPort}`); + } + log.log( 'ChromeLauncher', `No debugging port found on port ${this.port}, launching a new Chrome.`);