Solvedlighthouse Using lighthouse in combination with Puppeteer

Hello,

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 = 'https://www.chromestatus.com/features';

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:

21
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...
19
lighthouse ECONNREFUSED error, I don't understand...
@sonyarianto I was experimenting the same issue on Chrome 60 and adding --no-sandbox flag solved the...
17
lighthouse Question: How to test page behind authentication?
Just a comment if you're using basic authentication you can run lighthouse this way: ...
17
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 ...
16
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 ...
188
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 --...
19
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...
8
aspnetboilerplate Hangfire RecurringJob module integration
@maharatha Of course; Hi Halil There is a module in abp; PeriodicBackgroundWorker that is doing same...
3
aspnetboilerplate MVC SPA Template is broken
hi guys !! i have good news !! at least searching for a solution i have found this ...
3
aspnetboilerplate Castle.MicroKernel.CircularDependencyException when resolving MvcRouteHandler
Try this: Create AbpPropertiesDependenciesModelInspector class as shown below: Go to your Startup.cs...
121
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...
11
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...
7
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 ...
425
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...
365
puppeteer How to get text from a element ?
You can try this: or this: This might be a Obvious question but ...
326
puppeteer Chrome Headless doesn't launch on Debian
for the dockerisers amongst us - i've launched successfully with this setup: Running this example co...
285
puppeteer Ubuntu 18.04 Headless Chrome Node API - Puppeteer - Installation Guide
Based on https://github.com/GoogleChrome/puppeteer You only have to run the following command in Ubu...
252
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...
233
puppeteer Installation fails on Apple Silicon / M1
The solution for me using Chromium from Homebrew was: You will get a security warning ...
200
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...
162
puppeteer can't run puppeteer in centos7
@zhuyingda 's notes above will allow you to run puppeteer with --no-sandbox Server Info: CUP: Intel(...
155
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...
136
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 ...
116
puppeteer Run from Electron
For me the solution was a combination of the approach of @qathom and @tpkn: But in my case the array...
111
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....
102
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 ...
98
puppeteer ERROR:zygote_host_impl_linux.cc(89)] 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...
96
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: ...
81
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...
75
gitsome Command "python setup.py 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). ...
75
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...
68
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 ...
68
puppeteer EventEmitter memory leak detected. 11 exit listeners added
@selfrefactor ah indeed you launch chrome processes in parallel Every chrome instance adds a listene...
66
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...
64
puppeteer Puppeteer Won't Click on Element
In my case I'm able to use this reliably: page.$eval(selectorStr elem => elem.click()); ...
60
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 page.click ...
60
puppeteer Page.click() 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...
59
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...
57
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 ...
54
puppeteer Issue with deploying puppeteer on heroku (with resolution)
Did you try puppeteer.launch({args: ['--no-sandbox' '--disable-setuid-sandbox']});? ...
46
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 ...
39
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 ...
38
puppeteer Emit new Page objects when new tabs created
The target object is defined at https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#cl...
37
puppeteer Support OOPIF
While we're figuring this out a workaround is to run with --disable-features=site-per-process flag: ...
37
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 ...
36
puppeteer How to stop puppeteer follow redirects
Coupling request interception with request.isNavigationRequest and request.redirectChain you can now...
35
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...
34
puppeteer Certificates error using puppeteer
You can also set an args array inside the launch config args: [ '--ignore-certificate-errors' ] I ha...
34
puppeteer Click event is not firing
The following works for me Note the 'networkidle' argument for page.goto Also the delay in typing is...
33
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...