Solvedlighthouse Using lighthouse in combination with Puppeteer


I'm would like to launch a chrome instance, connect puppeteer to it to login, and then start lighthouse, is that possible ? I couldn't find a way to connect puppeteer to a chrome instance started with chrome-launcher.

I've tried something like this but with no success

function launchChromeAndRunLighthouse(url, opts, config = null) {
	return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(async chrome => {
		opts.port = chrome.port;
		const url = 'ws://localhost:' + chrome.port + '/devtools/browser/';
		const browser = await puppeteer.connect({
			browserWSEndpoint: url
                // this throws the following WS error: (node:9000)
                // UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: unexpected server response (404)

because I'm missing the browser id after browser/ and it doesn't seem to be exposed by lighthouse

I've seen issues where it says to manually connect before running lighthouse on a website where login is mandatory. Is there any other fully automated way to do this ?

18 Answers

✔️Accepted Answer

This should work:

const chromeLauncher = require('chrome-launcher');
const puppeteer = require('puppeteer');
const lighthouse = require('lighthouse');
const request = require('request');
const util = require('util');

(async() => {

const URL = '';

const opts = {
  //chromeFlags: ['--headless'],
  logLevel: 'info',
  output: 'json'

// Launch chrome using chrome-launcher.
const chrome = await chromeLauncher.launch(opts);
opts.port = chrome.port;

// Connect to it using puppeteer.connect().
const resp = await util.promisify(request)(`http://localhost:${opts.port}/json/version`);
const {webSocketDebuggerUrl} = JSON.parse(resp.body);
const browser = await puppeteer.connect({browserWSEndpoint: webSocketDebuggerUrl});

// Run Lighthouse.
const lhr = await lighthouse(URL, opts, null);
console.log(`Lighthouse score: ${lhr.score}`);

await browser.disconnect();
await chrome.kill();


Related Issues:

lighthouse Crashes on Docker with emulated-form-factor=desktop
I've had the same issue and found a workaround Apparently chrome relies on shared memory which is mo...
lighthouse ECONNREFUSED error, I don't understand...
@sonyarianto I was experimenting the same issue on Chrome 60 and adding --no-sandbox flag solved the...
lighthouse Question: How to test page behind authentication?
Just a comment if you're using basic authentication you can run lighthouse this way: ...
lighthouse Is there a way to generate html report using lighthouse programmatically.
@patrickhulce thank you for that! I'm still confused and I did it work in a hacky way All I want is ...
lighthouse Using lighthouse in combination with Puppeteer
This should work: Hello I'm would like to launch a chrome instance connect puppeteer to it to login ...
laravel activitylog >PHP7.2: Declaration of Orchestra\Testbench\TestCase::setUp() must be compatible with PHPUnit\Framework\TestCase::setUp()
@AndresMatta in TestCase.php file add :void public function setUp(): void phpunit --coverage-text --...
WebFundamentals ERROR: Failed to resolve: com.github.GoogleChrome.custom-tabs-client:customtabs:d08e93fce3
Okay.. sorry for referencing any of the contributors.. nothing is more frustrating than a failed bui...
aspnetboilerplate Hangfire RecurringJob module integration
@maharatha Of course; Hi Halil There is a module in abp; PeriodicBackgroundWorker that is doing same...
aspnetboilerplate MVC SPA Template is broken
hi guys !! i have good news !! at least searching for a solution i have found this ...
aspnetboilerplate Castle.MicroKernel.CircularDependencyException when resolving MvcRouteHandler
Try this: Create AbpPropertiesDependenciesModelInspector class as shown below: Go to your Startup.cs...
remotedebug ios webkit adapter Windows not able to inspect iOS 11
I finally got it to work with a lot of failed attempts Here were my steps for any future users attem...
remotedebug ios webkit adapter Nothing to inspect in chrome://inspect/#devices on iPad iOS 13.3
Also having this issue with both iPhone 6s and iPad Pro with iOS version 13.3 when trying to inspect...
chromedp An example to capture a screenshot of the full page
Here's what I'm using As a bonus it also handles page scaling Click to expand Is it possible to get ...
puppeteer Failed to download Chromium r536395! Set "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variable to skip download.
Solves the issue to me. Steps to reproduce Tell us about your environment: Puppeteer version: Not in...
puppeteer How to get text from a element ?
You can try this: or this: This might be a Obvious question but ...
puppeteer Chrome Headless doesn't launch on Debian
for the dockerisers amongst us - i've launched successfully with this setup: Running this example co...
puppeteer Ubuntu 18.04 Headless Chrome Node API - Puppeteer - Installation Guide
Based on You only have to run the following command in Ubu...
puppeteer how to check if selector exists or is present ?
As a variant: how to check if selector exists or is present waiting for (x) time or when the page is...
puppeteer Installation fails on Apple Silicon / M1
The solution for me using Chromium from Homebrew was: You will get a security warning ...
puppeteer npm install -g puppeteer fails
This command ended up working for me in case anyone lands here by googling the error: sudo npm insta...
puppeteer can't run puppeteer in centos7
@zhuyingda 's notes above will allow you to run puppeteer with --no-sandbox Server Info: CUP: Intel(...
puppeteer Headless mode is not working
I had the same issue I then added await page.screenshot(...) to see what's going on in headless mode...
terragrunt Upgrading to Terraform 0.12: separate configuration file for Terragrunt?
Hi all Hi! I'm one of the engineers at HashiCorp who works on Terraform Core As you might be aware ...
puppeteer Run from Electron
For me the solution was a combination of the approach of @qathom and @tpkn: But in my case the array...
zeal Content rendering error in MDN (HTML, JS, CSS) docsets
I find it can fix temporary by remove the CSS.docset\Contents\Resources\Documents\developer.mozilla....
puppeteer How to scrape an element
The following should work: Hi I think this is an obvious question but still I cannot figure out how ...
puppeteer] Running as root without --no-sandbox is not supported
@ststeiger so which are the launch options? Like Or do I need to add args: ['--no-sandbox' '--disabl...
puppeteer Page.setContent should wait for resources to be loaded
Meanwhile a good workaround for page.setContent that waits for all the resources to load: ...
puppeteer Request: browser.currentPage() or similar way to access Pages
To get the first page of the current browser I was playing around with Puppeteer today and I found o...
gitsome Command "python egg_info" failed with error code 1 in /tmp/pip-build-7SrToZ/gitsome/
I had the same problem on OSX and Solve my issue (I have both python versions installed). ...
puppeteer Error: Failed to launch chrome! spawn /app/node_modules/puppeteer/.local-chromium/linux-609904/chrome-linux/chrome ENOENT
@arapocket Thanks for commenting—I forgot to follow up after I found a solution It's been a couple o...
puppeteer Error: Failed to launch the browser process! spawn chrome.exe ENOENT
For me on Linux the only way to resolve is by installing some dependencies: Source ...
puppeteer EventEmitter memory leak detected. 11 exit listeners added
@selfrefactor ah indeed you launch chrome processes in parallel Every chrome instance adds a listene...
puppeteer Collect element attributes from selector
i think this would do it And once #625 is implemented this will be.. Beginner user here Started play...
puppeteer Puppeteer Won't Click on Element
In my case I'm able to use this reliably: page.$eval(selectorStr elem =>; ...
puppeteer Execution context was destroyed, most likely because of a navigation
@THE-GAME-YOU-LOST I see The right thing to do would be to await navigation caused by ...
puppeteer does not work with an input selector
I'm running into the same issue Strangely if I use page.evaluate it does work For example: I'd be cu...
puppeteer Different behavior between { headless: false } and { headless: true }
As mentioned in the article @Garbee posted the headless version does not have languages set on the n...
puppeteer Puppeteer with headless:true is extremely slow
Hey guys so I've found a workaround for this Though this issues has been raised in #1550 but it was ...
puppeteer Issue with deploying puppeteer on heroku (with resolution)
Did you try puppeteer.launch({args: ['--no-sandbox' '--disable-setuid-sandbox']});? ...
puppeteer Query nodes within shadow roots
TL;DR: try Copy JS Path in Chrome Canary to get a js selector for nodes inside Shadow DOM ...
puppeteer Issue when deploying with node:8-alpine (docker)
Can we re-open this? There doesn't seem to be a documented solution for running Puppeteer on Alpine ...
puppeteer Emit new Page objects when new tabs created
The target object is defined at
puppeteer Support OOPIF
While we're figuring this out a workaround is to run with --disable-features=site-per-process flag: ...
puppeteer Support browser contexts to launch different sessions
Ok I got this working Thanks for the tip @ks07 UPDATE (2017-11-04): I've updated the example with a ...
puppeteer How to stop puppeteer follow redirects
Coupling request interception with request.isNavigationRequest and request.redirectChain you can now...
puppeteer Error generating PDFs: Protocol error (Page.printToPDF): Target closed.
Was getting the same error on pptr v1.12.2 but was able to fix it by setting pipe: true when launchi...
puppeteer Certificates error using puppeteer
You can also set an args array inside the launch config args: [ '--ignore-certificate-errors' ] I ha...
puppeteer Click event is not firing
The following works for me Note the 'networkidle' argument for page.goto Also the delay in typing is...
puppeteer Ability to prevent header/footer on certain pages
I hope this solution helps someone even though it's super hacky I had a need to remove the header on...