Coder Social home page Coder Social logo

googlechrome / chrome-launcher Goto Github PK

View Code? Open in Web Editor NEW
1.2K 41.0 183.0 15.78 MB

Launch Google Chrome with ease from node.

Home Page: https://www.npmjs.com/package/chrome-launcher

License: Apache License 2.0

TypeScript 91.24% JavaScript 5.51% Shell 3.25%

chrome-launcher's Introduction

Chrome Launcher GitHub Actions Status Badge NPM chrome-launcher package

Launch Google Chrome with ease from node.

  • Disables many Chrome services that add noise to automated scenarios
  • Opens up the browser's remote-debugging-port on an available port
  • Automagically locates a Chrome binary to launch
  • Uses a fresh Chrome profile for each launch, and cleans itself up on kill()
  • Binds Ctrl-C (by default) to terminate the Chrome process
  • Exposes a small set of options for configurability over these details

Once launched, interacting with the browser must be done over the devtools protocol, typically via chrome-remote-interface. For many cases Puppeteer is recommended, though it has its own chrome launching mechanism.

Installing

yarn add chrome-launcher

# or with npm:
npm install chrome-launcher

API

.launch([opts])

Launch options

{
  // (optional) remote debugging port number to use. If provided port is already busy, launch() will reject
  // 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
  chromeFlags: Array<string>;

  // (optional) Additional preferences to be set in Chrome, for example: {'download.default_directory': __dirname}
  // See: https://chromium.googlesource.com/chromium/src/+/main/chrome/common/pref_names.cc
  // Do note, if you set preferences when using your default profile it will overwrite these
  prefs: {[key: string]: Object};

  // (optional) Close the Chrome process on `Ctrl-C`
  // Default: true
  handleSIGINT: boolean;

  // (optional) Explicit path of intended Chrome binary
  // * If this `chromePath` option is defined, it will be used.
  // * Otherwise, the `CHROME_PATH` env variable will be used if set. (`LIGHTHOUSE_CHROMIUM_PATH` is deprecated)
  // * Otherwise, a detected Chrome Canary will be used if found
  // * Otherwise, a detected Chrome (stable) will be used
  chromePath: string;

  // (optional) Chrome profile path to use, if set to `false` then the default profile will be used.
  // By default, a fresh Chrome profile will be created
  userDataDir: string | boolean;

  // (optional) Starting URL to open the browser with
  // Default: `about:blank`
  startingUrl: string;

  // (optional) Logging level
  // Default: 'silent'
  logLevel: 'verbose'|'info'|'error'|'silent';

  // (optional) Flags specific in [flags.ts](src/flags.ts) will not be included.
  // Typically used with the defaultFlags() method and chromeFlags option.
  // Default: false
  ignoreDefaultFlags: boolean;

  // (optional) Interval in ms, which defines how often launcher checks browser port to be ready.
  // Default: 500
  connectionPollInterval: number;

  // (optional) A number of retries, before browser launch considered unsuccessful.
  // Default: 50
  maxConnectionRetries: number;

  // (optional) A dict of environmental key value pairs to pass to the spawned chrome process.
  envVars: {[key: string]: string};
};

Launched chrome interface

.launch().then(chrome => ...

// The remote debugging port exposed by the launched chrome
chrome.port: number;

// Method to kill Chrome (and cleanup the profile folder)
chrome.kill: () => Promise<void>;

// The process id
chrome.pid: number;

// The childProcess object for the launched Chrome
chrome.process: childProcess

ChromeLauncher.Launcher.defaultFlags()

Returns an Array<string> of the default flags Chrome is launched with. Typically used along with the ignoreDefaultFlags and chromeFlags options.

Note: This array will exclude the following flags: --remote-debugging-port --disable-setuid-sandbox --user-data-dir.

ChromeLauncher.Launcher.getInstallations()

Returns an Array<string> of paths to available Chrome installations. When chromePath is not provided to .launch(), the first installation returned from this method is used instead.

Note: This method performs synchronous I/O operations.

.killAll()

Attempts to kill all Chrome instances created with .launch([opts]). Returns a Promise that resolves to an array of errors that occurred while killing instances. If all instances were killed successfully, the array will be empty.

import * as ChromeLauncher from 'chrome-launcher';

async function cleanup() {
  await ChromeLauncher.killAll();
}

Examples

Launching chrome:

import * as ChromeLauncher from 'chrome-launcher';

ChromeLauncher.launch({
  startingUrl: 'https://google.com'
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});

Launching headless chrome:

import * as ChromeLauncher from 'chrome-launcher';

ChromeLauncher.launch({
  startingUrl: 'https://google.com',
  chromeFlags: ['--headless', '--disable-gpu']
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});

Launching with support for extensions and audio:

import * as ChromeLauncher from 'chrome-launcher';

const newFlags = ChromeLauncher.Launcher.defaultFlags().filter(flag => flag !== '--disable-extensions' && flag !== '--mute-audio');

ChromeLauncher.launch({
  ignoreDefaultFlags: true,
  chromeFlags: newFlags,
}).then(chrome => { ... });

Continuous Integration

In a CI environment like Travis, Chrome may not be installed. If you want to use chrome-launcher, Travis can install Chrome at run time with an addon. Alternatively, you can also install Chrome using the download-chrome.sh script.

Then in .travis.yml, use it like so:

language: node_js
install:
  - yarn install
before_script:
  - export DISPLAY=:99.0
  - export CHROME_PATH="$(pwd)/chrome-linux/chrome"
  - sh -e /etc/init.d/xvfb start
  - sleep 3 # wait for xvfb to boot

addons:
  chrome: stable

chrome-launcher's People

Contributors

adamraine avatar ajoy39 avatar alexhorn avatar also avatar brendankenny avatar christian-bromann avatar connorjclark avatar devrelm avatar flotwig avatar g-rath avatar gudahtt avatar iominh avatar junyan avatar kyivjunta avatar mariyan-borisov avatar mathiasbynens avatar mikecardwell avatar mixed avatar molant avatar niek avatar patrickhulce avatar paulirish avatar pmeinhardt avatar rishi-raj-jain avatar saafine avatar samccone avatar sinaa avatar takenspc avatar wardpeet avatar westy92 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chrome-launcher's Issues

Launcher ECONNREFUSED flake

From @paulirish on June 20, 2017 21:59

This is a bit of carryover from #2544. It was failing 100% of the time and now its more like 5%.

Example build: https://travis-ci.org/GoogleChrome/lighthouse/jobs/245116083
image

Things to note:

  • Last night, this error thrown for EVERY chrome launch, like all smokehouse runs. After ward's fix it appears to only affect the Launcher tests
  • It's intermittent. On this build, only 1 of the 3 travis jobs had a problem.

There might be still a bug on the travis/chrome side, but seems like we have room to handle this from within launcher. (port sniffing & retry logic?)
At the very least, more usable error messages and extra logging.

wdyt @samccone

edit: he said..

image

Copied from original issue: GoogleChrome/lighthouse#2556

Android chrome launcher via ADB

from GoogleChrome/lighthouse#910:


Running lighthouse currently on an android phone is pretty tedious.

Ideally a user should be able to run lighthouse and pick a connected android phone to run chrome on and run the selected audits.

Implementations steps.

  1. detect if adb is in the path or set via ADB_PATH
  2. adb devices -l to get the connected devices
  3. present the list of devices to pick from
  4. detect is chrome canary installed, if not bail.
  5. launch chrome canary on the device
  6. setup port forwarding from device
    adb forward tcp:9222 localabstract:chrome_devtools_remote
  7. run lighthouse 💃

I think we could exclude support for multiple devices for the moment. I personally get nervous to have multiple devices connected over adb and trust that the right commands will go to the right phone, so I always unplug the one i'm not working with. But if you'd rather keep it in scope, then sure. :)

How do you want to handle getting a clean baseline? Clean chrome profile? Can we do user-data-dir via flag on android? Do we only use Canary and say "We'll be wiping your storage and SWs, FYI!"?

Running multiple headless chrome instances

I need to run multiple headless chrome instances in parallel in order to efficiently generate output by processing DOM information from Jupyter notebooks. Each headless chrome instance is launched by executing the following method:

function launchChrome() {
    return chromeLauncher.launch({
        port: 9222,
        autoSelectChrome: true,
        chromeFlags: [
            '--headless',
            '--disable-gpu',
            '--no-sandbox',
            '--allow-running-insecure-content',
            '--window-size=1750,1100',
            '--enable-experimental-web-platform-features',
            '--hide-scrollbars',
        ],
        // Uncomment to receive logging from the headless chrome launcher itself
        logLevel: 'verbose'
    });

Additionally, I attach an instance of chrome-remote-interface to each headless chrome instance in order to access the DOM and each instance points to the URL specified in urlName by executing:

Page.navigate({ url: urlName });

When I try to execute my nodejs script which launches an instance of headless chrome as so:

/usr/local/bin/n use 8.8.1 /home/ubuntu/notebook_server/notebook/services/reporting/js/report.js <urlName>

two times with two different URL's the output of the first command coming from the chrome launcher is

  ChromeLauncher No debugging port found on port 9222, launching a new Chrome. +0ms
  ChromeLauncher:verbose created /tmp/lighthouse.nR4usdT +6ms
  ChromeLauncher:verbose Launching with command:
  ChromeLauncher:verbose "/usr/bin/google-chrome" --disable-translate --disable-extensions --disable-background-networking --safebrowsing-disable-auto-update --disable-sync --metrics-recording-only --disable-default-apps --no-first-run --remote-debugging-port=9222 --user-data-dir=/tmp/lighthouse.nR4usdT --disable-setuid-sandbox --headless --disable-gpu --no-sandbox --allow-running-insecure-content --window-size=1750,1100 --enable-experimental-web-platform-features --hide-scrollbars about:blank +15ms
  ChromeLauncher:verbose Chrome running with pid 1472 on port 9222. +2ms
  ChromeLauncher Waiting for browser. +1ms
  ChromeLauncher Waiting for browser... +0ms
  ChromeLauncher Waiting for browser..... +503ms
  ChromeLauncher Waiting for browser.....✓ +1ms
Default extension for cell metadata editing loaded.
Raw Cell Format toolbar preset loaded.
Slideshow extension for metadata editing loaded.
Session: kernel_created (0c44f3ce-925b-4b12-bfba-69eacb2b8b57)
Starting WebSockets:
{ pageHeight: 1100 }
Kernel: kernel_connected (5ac7d8ed-cf58-41b9-a58f-cb583df1d8cb)
Kernel: kernel_ready (5ac7d8ed-cf58-41b9-a58f-cb583df1d8cb)

and the output of the second command is:

Default extension for cell metadata editing loaded.
Raw Cell Format toolbar preset loaded.
Slideshow extension for metadata editing loaded.
Session: kernel_created (0c44f3ce-925b-4b12-bfba-69eacb2b8b57)
Starting WebSockets:
{ pageHeight: 1100 }
Kernel: kernel_connected (5ac7d8ed-cf58-41b9-a58f-cb583df1d8cb)
Kernel: kernel_ready (5ac7d8ed-cf58-41b9-a58f-cb583df1d8cb)
going to check if all iframes are rendered again in 3 seconds
still waiting on some iframes
Default extension for cell metadata editing loaded.
Raw Cell Format toolbar preset loaded.
Slideshow extension for metadata editing loaded.
Session: kernel_created (a71ac924-f942-44ee-8b9e-a65f26fdf7af)
Starting WebSockets:
{ pageHeight: 2733 }
Kernel: kernel_connected (6105e198-23bc-4304-b678-d7cb33b4197c)
Kernel: kernel_ready (6105e198-23bc-4304-b678-d7cb33b4197c)

Indicating that the chrome that was launched by the second command is that same. Or is the output stream shared? Either way my DOM process code executes and completes from the first invocation but not the second. It just seems to hang.

Any chance you could enlighten me as to whether or not two headless chrome processes can run independently of each other?

chrome-launcher doesn`t propogate errors if some flag is a empty string

if some flag is set to a empty string chrome launcher doesnt add the error in staring chrome in the stack strace . Have included the sample code here since we are not setting proxy variable in our config an empty flag is being passed to chrome launcher . chrome fails to launch but this doesnt show up in the log .any work around for it so it shows up in error

try {
      chromeInstance = await chromeLauncher.launch({
        port: 9222,
        chromeFlags: [
          '--disable-gpu',
          '--hide-scrollbars',
          headless ? '--headless' : '',
          config.proxy ? `--proxy-server=${config.proxy}` : '',
        ],
        handleSIGINT: true,
      });
      logger.debug({
        [logger.fields.description]: 'CHROME_LAUNCHED',
        [logger.fields.object]: JSON.stringify(chromeInstance),
      });
      lock.releaseLock();
    } catch (error) {
      lock.releaseLock();
      logger.warn({
        [logger.fields.description]: 'ERROR_LAUNCHING_CHROME',
        [logger.fields.stack_trace]: error.stack,
      });
      throw error;
    }
  }

How to obtain the websocket URL?

I would like to spin up multiple instances using chrome-launcher and then connect to them using Puppeteer. It is not clear how to obtain the websocket URL of the headless Chrome instance, e.g. ws://127.0.0.1:9222/devtools/browser/d9f8012e-94b8-4441-ad1e-1cf8de94e57f.

chrome-launcher only gives the port number. I have tried ws://127.0.0.1:${obtained port number}, but I am getting 404.

Bikeshed changing default chrome flags used.

Breaking this out from #38 where we explored this the most. cc @ragingwind

Here is the node module API implemented in #38 (let's call this JS vAlpha API):

chromeLauncher.defaultFlags() // array of all the flags it uses by default

chromeLauncher.launch({
  ignoreDefaultFlags: true,  // will not supply any defaults.. the ones passed in below are it.
  chromeFlags: [] // array of the only flags to use
});

and a CLI vAlpha API:

chrome-launcher --list-flags # prints and quits: '--disable-extensions --disable-translate-service ....'

chrome-launcher # launches with default flags
chrome-launcher --set-flags="--show-paint-rects --disable-extensions"   # skips default flags and only uses provided ones
# naming: maybe "override-flags" to indicate this may break things..

# also allow just augmenting default flags with --add-flags
chrome-launcher --add-flags="--show-paint-rects"
# (this behavior is what lighthouse's current --chrome-flags arg does)

add support for `pollInterval` or `pollRetries` as an option

From @alekseykulikov on August 24, 2017 9:17

Currently pollInterval = 500 ms and pollRetries = 10 are hard-coded. It means, that launcher waits approximately 5s and then fails.
Sometimes, this is time not enough to start a Chrome, especially on slow machines or first boot inside new env.
I'd like to provide a PR, but first I'd like to hear feedback, should it be only pollRetries or both.

Copied from original issue: GoogleChrome/lighthouse#3110

ES6 default import does not work

Hi,

Problem

I was trying to import the chrome-launcher using default import syntax like that:

import chromeLauncher from 'chrome-launcher';

However, when I tried using it I got an error messageL ReferenceError: chromeLauncher is not defined.

Workaround

Importing all of the modules contents works.

import * as chromeLauncher from 'chrome-launcher';

I suggest either explicitly stating in the documentation that the modules has to be imported with import all contents syntax or add support for the default import.

Chrome launches in broken/non-functional state on Windows from Admin console

From @mmanela on August 23, 2017 16:48

This is the same bug reported on karma-chrome-launcher. If you open chrome using the chrome-launcher from an admin process, it open as a "dead" browser tab.

REPRO

  1. Open an admin command prompt (Repro'd on Windows 10.0.15063)
  2. Run Node ( I am using v8.4.0)
  3. let launcher = require('chrome-launcher')
  4. launcher.launch()
  5. Launches dead chrome that is not functional (can't go to any page)
    image

If I do the same steps from a non-admin command prompt this works.

Copied from original issue: GoogleChrome/lighthouse#3099

finder: Failing to find google-chrome binary on centos 7

Reported by @jayflux

CHROME_PATH=/usr/bin/google-chrome
NODE_EXTRA_CA_CERTS=/etc/pki/tls/certs/ca-bundle.crt
_=/usr/bin/env
[developer@sounds-performance sounds-performance]$ sudo -E node index.js 
which: no chromium-browser in (/sbin:/bin:/usr/sbin:/usr/bin)
which: no chromium in (/sbin:/bin:/usr/sbin:/usr/bin)
{ Error: connect ECONNREFUSED 127.0.0.1:33429
    at Object._errnoException (util.js:1024:11)
    at _exceptionWithHostPort (util.js:1046:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 33429 }
[developer@sounds-performance sounds-performance]$ 
  1. google-chrome installed via YUM on centos 7. chrome-finder is failing to locate it.
  2. and the explicit CHROME_PATH setting doesn't seem to fix things.

handleSIGINT: false not working

I'm setting handleSIGINT: false
When i press ctrl + c chrome closes, which it shouldn't
Running on OSX High Sierra, Chrome 63.0.3239.108

How to use default userDataDir on launch?

Is it possible to launch chrome without creating a new userDataDir?
From what I read in the documentation I will have to pass the user's current userDataDir as part of the launch options but that doesn't look OK to me. The developer will have to detect the platform and user name to generate the right path (C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default, Users/<username>/Library/Application Support/Google/Chrome/Default, /home/<username>/.config/google-chrome/default, for example).

The scenario I have in mind is to easily allow automation of some pages behind authentication if the user is already authenticated in there, for example.

Will you be open to have something to enable this? If so, what would be your preferred option? New parameter? Special value in userDataDir (maybe default)?

Cannot read property 'kill' of undefined

From @Sudarson59 on March 1, 2017 13:37

When I run lighthouse I stuck at the below error in launching chrome browser,

Chrome: 56.0.2924.87 (64-bit)
LIGHTHOUSE_CHROMIUM_PATH = /usr/bin/google-chrome-stable

Lighthouse Cli invocation
./lighthouse http://abcd.test.com/ --verbose
Lighthouse CLI:verbose Using supplied port 9222 +0ms
Lighthouse CLI Launching Chrome... +8ms
ChromeLauncher:verbose created /tmp/lighthouse.rmRno9z +7ms
ChromeLauncher:verbose Chrome running with pid 24444 on port 9222. +25ms
ChromeLauncher Waiting for browser. +0ms
ChromeLauncher Waiting for browser... +1ms
ChromeLauncher Waiting for browser..... +504ms
ChromeLauncher Waiting for browser....... +501ms
ChromeLauncher Waiting for browser......... +502ms
ChromeLauncher Waiting for browser........... +501ms
ChromeLauncher Waiting for browser............. +501ms
ChromeLauncher Waiting for browser............... +502ms
ChromeLauncher Waiting for browser................. +501ms
ChromeLauncher Waiting for browser................... +501ms
ChromeLauncher Waiting for browser..................... +502ms
ChromeLauncher Waiting for browser....................... +501ms
(node:24423) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'kill' of undefined

Chrome Error Log:
[24444:24444:0301/185543.506507:FATAL:zygote_host_impl_linux.cc(107)] No usable sandbox! Update your kernel or see https://chromium.googlesource.com/chromium/src/+/master/docs/linux_suid_sandbox_development.md for more information on developing with the SUID sandbox. If you want to live dangerously and need an immediate workaround, you can try using --no-sandbox.

I passed --no-sandbox in chrome-launcher.js and it re-run the lighthouse command and it worked fine.

Changes to chrome-launcher.js
const flags = [
--remote-debugging-port=${this.port},
'--no-sandbox', //added no sandbox option
]

How to provide this flag as an option from lighthouse cli? or How to overcome the issue mentioned above.

Copied from original issue: GoogleChrome/lighthouse#1799

Add ability to pass environment variables for launched Chrome process (to set TZ)

I have a use case where I need to launch Chrome with a different "TZ" variable than the one the environment is running under.

While I can do this in my launching Node process, it would make my script easier if I had a way to pass TZ into the launcher.

If you accept env as a launcher option, it would then get passed along into spawn command here: https://github.com/GoogleChrome/chrome-launcher/blob/master/chrome-launcher.ts#L220

Format of env argument could be something like this for example:

env: { 'TZ': 'America/New_York'}

docs improvement - open browser in a new tab or a new window

in the readme, it doesn't look like there is an option to open a new window in chrome or just a new tab

last time I looked in the codebase, I believe it defaults to opening a new tab (it tries it's best to).

is there some flag to force opening a new window? should that be documented?

Does it make sense to expose an option in lighthouse core to launch chrome?

From @samccone on May 16, 2017 3:54

The common use-case for using lighthouse programmatically is to launch chrome with it.. right now that is a nested promise with a bit of clean up at the end... The reason for most of this work boils down to the need to pass port from the launcher to lighthouse.. because of this I think it might be nice to do something like

flags.launchChrome = true;
return Lighthouse(url, flags, config);

Which would take care of killing and launching chrome.

Copied from original issue: GoogleChrome/lighthouse#2259

WSL: Runtime error encountered

I get the following error in WSL when running smokehouse in lighthouse.

Runtime error encountered: { Error: EINVAL: invalid argument, mkdir '/mnt/c/Users/WardPeeters/Projects/os/lighthouse/node_modules/.bin:'

My path env is the following:

/mnt/c/Users/<user>/Projects/os/lighthouse/node_modules/.bin:/usr/local/share/.config/yarn/link/node_modules/.bin:/mnt/c/Users/<user>/Projects/os/lighthouse/node_modules/.bin:/usr/local/share/.config/yarn/link
/node_modules/.bin:/root/.nvm/versions/node/v8.9.3/lib/node_modules/npm/bin/node-gyp-bin:/root/.nvm/versions/node/v8.9.3/bin/node_modules/npm/bin/node-gyp-bin:/mnt/c/Users/<user>/Projects/os/lighthouse/node_modules/.b
in:/usr/local/share/.config/yarn/link/node_modules/.bin:/mnt/c/Users/<user>/Projects/os/lighthouse/node_modules/.bin:/usr/local/share/.config/yarn/link/node_modules/.bin:/root/.nvm/versions/node/v8.9.3/lib/node_module
s/npm/bin/node-gyp-bin:/root/.nvm/versions/node/v8.9.3/bin/node_modules/npm/bin/node-gyp-bin:/root/.nvm/versions/node/v8.9.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt
/c/Program Files/Docker/Docker/resources/bin:/mnt/c/Windows/System32:/mnt/c/Windows:/mnt/c/Windows/System32/wbem:/mnt/c/Windows/System32/WindowsPowerShell/v1.0:/mnt/c/ProgramData/chocolatey/bin:/mnt/c/Program Files/dotnet:
/mnt/c/Program Files/Microsoft SQL Server/130/Tools/Binn:/mnt/c/Users/<user>/AppData/

Update maxConnectionRetries default to 50 in docs

Hi there!

maxConnectionRetries is documented with a default of 10 in README.md.

It's actual default is 50 (in chrome-launcher.ts).

Should the readme be updated, or should the default be adjusted? A default of 50 retries with default connectionPollInterval of 500ms seems like a really long time.

Request: Expose the browser ID when launching

From @joelgriffith on August 7, 2017 17:40

When launching Chrome (at 62) it prints the special "browser" target to connect to:

DevTools listening on ws://127.0.0.1:9222/devtools/browser/dce23e24-5a5b-4f89-a3f4-749d3ef70ea9

This target isn't exposed/discoverable anywhere else in the protocol due to this merge: https://chromium-review.googlesource.com/c/596719

It might be a good thing to expose to consumers so that they can attach to this special target and do commands at the browser-level

Copied from original issue: GoogleChrome/lighthouse#2865

Add support for WSL on Windows 10

Starting on build 14951 WSL supports opening windows applications from bash. This will be available for anyone in the next stable release of Windows in October 17th

Bash on Windows is becoming very popular and adding support to this will be great. We've had a few people run into this issue when using sonar.

I can probably look into adding this if no one else wants to 😊

Allow mute-audio flag to be disabled

I understand the majority of users will want muted audio during automated testing, but in our case we are recording video of the browsers tests and would like to record any audio generated by the browser. I'm sure others with multimedia sites may need access to this functionality. Although audio can't easily be automatically tested for, it is useful and simpler to watch the automated test case videos to check functionality rather than having to manually test audio functionality separately.

As this flag is in the defaults, there appears to be no way to override the behaviour (short of forking the entire code).

Would it be possible to make this a non-default flag, as an option that defaults to true, or an --unmute-audio flag, that pops the --mute-audio from the defaults?

this vs. puppeteer - launch browser to automatically stop at breakpoints

Hey all, looks like puppeteer will stop at breakpoints/debugger statements if devTools is set to true:

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions

Is there a way to do the same thing with chrome-launcher, or should I use puppeteer instead? I am not even sure what the difference is between puppeteer and chrome-launcher, would be nice for a brief compare and contrast in the README?

How to listen for browser close event

I see that chrome-launcher allows us to kill the browser. However if the browser closes itself (window.close() I believe it is), is there a way to listen for when the browser process ends using this library?

lighthouse opens chrome with about:blank tabs

From @guilhermevrs on July 19, 2017 9:32

Initial URL: https://developers.google.com/web/tools/lighthouse/
Chrome Version: 61.0.3160.0

When lauching
./node_modules/.bin/lighthouse https://developers.google.com/web/tools/lighthouse/

I get the following:

  ChromeLauncher Waiting for browser. +0ms
  ChromeLauncher Waiting for browser... +2ms
  ChromeLauncher Waiting for browser...√ +510ms

But a chrome canary window opens with three tabs untitled tabs. The first with the path of my chrome executable (e.g. file:///C:/Users/username/AppData/Local/Google/Chrome%20SxS/Application/61.0.3160.0) and the rest with about:blank

image

I can't open the DevTools on it.
I have tried to use remote debugging, but the "Inspected pages" shows nothing.

I have tried using programatically, but no luck either. Same results

Windows 7 x64
Lighthouse version: 2.2.1
Node version: 6.10.3

Copied from original issue: GoogleChrome/lighthouse#2711

Get remote debugging url

I have this:

const cl = require('chrome-launcher');
const util = require('util');

cl.launch({
  startingUrl: `http://yahoo.com`,
  chromeFlags: ['--auto-open-devtools-for-tabs', '--debug-devtools'],
  enableExtensions: true
})
.then(c => {
  console.log(util.inspect(c));
  // const url = c.getWebSocketServerUrl()
});

I am looking to get access to the url of the websocket server in the browser to connect to,
note that if I use these chrome flags

  chromeFlags: ['--auto-open-devtools-for-tabs', '--remote-debugging-port=9222'],

the Promise callback will never fire with the above chrome flags!

if you look at this issue:
puppeteer/puppeteer#1788

the way to get the remote debugging url, is with:

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserwsendpoint

browser.wsEndpoint()

returns: Browser websocket url.
Browser websocket endpoint which can be used as an argument to puppeteer.connect. The format is ws://${host}:${port}/devtools/browser/

my question is: is there a way to retrieve the remote debugging url given a launched chrome instance using chrome-launcher if we use the '--remote-debugging-port=9222' flag?

Force Chrome to pause at `debugger;` statements

I'd like to debug Google Chrome - using this module, is there a way to force Chrome to stop at the first debugger; statement? Is there a Chrome command line option for that? I have a codebase littered with debugger; statements, yet Chrome won't pause at them when I launch Chrome with chrome-launcher.

If you want some SO points, I have this question on there:
https://stackoverflow.com/questions/46881436/force-google-chrome-to-pause-at-breakpoints-debugger-statements

thanks

isDebuggerReady() net.createConnection ECONNREFUSED error in AWS ec2 instance

Hello

I was trying to run Rendertron using npm start in an AWS ec2 instance to avoid the docker container performance penalty.

then I got this error after npm start

[email protected] start /home/ec2-user/rendertron
node src/main.js
{ Error: connect ECONNREFUSED 127.0.0.1:33465
at Object._errnoException (util.js:1026:11)
at _exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1174:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 33465 }
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node src/main.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

The root of the problem was the isDebuggerReady() {} in chrome launcher. It seems that net.createConnection can never properly create a connection.

However, everything is running fine locally.

any ideas how to fix it?

Reproduction Steps

  1. start an AWS ec2 instance with AMI

  2. connect to the ec2 instance

  3. install git sudo yum install git

  4. pull rendertron repo

  5. git clone https://github.com/GoogleChrome/rendertron.git

  6. install chrome
    sudo yum --nogpgcheck localinstall https://intoli.com/blog/installing-google-chrome-on-centos/google-chrome-stable-60.0.3112.113-1.x86_64.rpm

  7. cd into rendertron folder cd rendertron

  8. npm install

  9. npm start

Tried work arounds

  • comment out yield this.waitUntilReady(); in chrome-launcher.js in the spawnProcess function. Rendertron was able to run, but if I try to render a page, it will give the following error.

Uncaught exception
{ Error: connect ECONNREFUSED 127.0.0.1:38585
at Object._errnoException (util.js:1026:11)
at _exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1174:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 38585 }

  • Increase the pollInterval to 50000ms. And simply the same result.
    net.createConnection() simply throws ECONNREFUSED error as soon as it tries to create a connection.

Thanks!

Final TODOs of chrome-launcher repo split

  • update repo in package.json
    • publish new version to NPM so links are updated.
      • update curl line in readme to use tagged URL instead.
  • add travis to this repo
  • add appveyor to repo
  • move download-chrome.sh from LH to launcher (and update launcher readme)
  • remove code from lighthouse
    • keep a stub readme.md in place to forward people
  • manually port over any pending PRs, branches.

Anything else?

Increase TCP buffer size for the chrome instance listening at a port.

  • I have created a chrome instance at a port(9222)
  • My application makes multiple simultaneous connections with the chrome instance.(close to 150 at a time).
  • I'm running into the following error - "request_sock_TCP: Possible SYN flooding on port 9222. Sending cookies. Check SNMP counters."
  • Is there a way to increase the TCP backlog buffer size(set for the socket when the 'listen' sys call is made) of the chrome instance listening at port 9222 ?
Component Version
Operating system Debian GNU/Linux buster/sid
Node.js v8.4.0
Chrome/Chromium/... 61.0.3163.91

Fails to find Chrome on Windows 10 latest, x64 in certain cases

Interestingly, using the same chrome-launcher, it seems like in certain running scenario's it fails to find Chrome. I encounter this using chromeless to create automated tests.

I've narrowed the cause down to https://github.com/GoogleChrome/chrome-launcher/blob/master/src/chrome-finder.ts#L170

If I change this on my local version to below it is solved. This is interesting mostly because ENV variables are supposed to be case sensitive on Windows and therefore Node.

const prefixes = [
    process.env.LOCALAPPDATA,
    process.env.LocalAppData,
    process.env.PROGRAMFILES,
    process.env.ProgramFiles,
    process.env["PROGRAMFILES(X86)"],
    process.env["ProgramFiles(x86)"]
  ].filter(Boolean);

I'm running node v8.9.4. The differences are in one case I call node index.js which starts a process, in the failing case I use the jest test runner. Both report the platform being win32 and end up in that part, I've got no clue how to find out where the issue would lie that suddenly makes the process.env.X accessing case sensitive.

Maybe add a notification on 'Close' event?

From @ghost on June 28, 2017 14:23

Greetings,

So, we're doing some unit testing of an application. One of such test is to launch a Chrome instance, run some JavaScript to close Chrome. After that, we have to test whether or not the Chrome is actually closed.

In current implementation of chrome-launcher, it's very hard to do so because there is no callback which will indicate a passive Chrome shutdown.

However, it seems that the child_process module is actually support exit event, so maybe it's possible to add a callback to notify the Chrome instance is gone?

Copied from original issue: GoogleChrome/lighthouse#2609

Support launching in Docker

We have a CI environment at my company that does not have chrome nor allows apt-get install on our machines, but docker is available for better isolation of these dependencies, but I see no documentation or support for Docker. This would be greatly appreciated. I'm trying to get a shell script put together that can achieve this by passing in as a CHROME_PATH, which may be the best, most unobtrustive way to support it. I'm struggling to get it working though :/

Bug/support - cannot load extensions page

I have this:

   chromeLauncher.launch({
      enableExtensions: true,
      startingUrl: 'chrome-extension://idbanmbeeadlaanhdemgngeooobbadde/dist/index.html'
    })
    .then(chrome => {
      console.log(`Chrome debugging port running on ${chrome.port}`);
    });

I get this:

screenshot from 2018-01-01 16-35-49

any idea why it can't load the extension's page?

by the way, I am trying to open it in a new tab in an existing window, but it keeps opening in a new window, let me know if there is some way to try to force it to use a tab instead of a new window. thx.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.