function launchChromeAndRunLighthouse(url, flags = {}, config = null) { return chromeLauncher.launch({chromeFlags: ['--disable-gpu', '--headless']}).then(chrome => { flags.port = chrome.port; return lighthouse(url, flags, config).then(results => chrome.kill().then(() => results)); }); }
/** * Attempts to connect to an instance of Chrome with an open remote-debugging * port. If none is found, launches a debuggable instance. * @param {LH.CliFlags} flags * @return {Promise<ChromeLauncher.LaunchedChrome>} */ function getDebuggableChrome(flags) { return ChromeLauncher.launch({ port: flags.port, chromeFlags: parseChromeFlags(flags.chromeFlags), logLevel: flags.logLevel, }); }
/** * Run lighthouse */ function launchChromeAndRunLighthouse(url, flags, config = null) { return chromeLauncher.launch().then(chrome => { flags.port = chrome.port; return lighthouse(url, flags, config).then(results => chrome.kill().then(() => results) ); }); }
promise = promise.then(() => { return ChromeLauncher.launch().then(launcher => { return singleRunAnalysis(url, launcher, {ignoreRun}) .catch(handleError) .then(() => launcher.kill()); }) .catch(handleError); });
function launchChromeAndRunLighthouse(url, flags, config) { return chromeLauncher.launch(CHROME_LAUNCH_OPTS).then(chrome => { flags.port = chrome.port; return lighthouse(url, flags, config). then(results => chrome.kill().then(() => results)). catch(err => chrome.kill().then(() => { throw err; }, () => { throw err; })); }); }
/** * Launches a debugging instance of Chrome. * @param {boolean=} headless True (default) launches Chrome in headless mode. * False launches a full version of Chrome. * @return {Promise<ChromeLauncher>} */ function launchChrome(headless=true) { return chromeLauncher.launch({ // port: 9222, // Uncomment to force a specific port of your choice. chromeFlags: [ '--window-size=1280,720', '--disable-gpu', headless ? '--headless' : '' ] }); }
async function launchChromeAndRunLighthouse(url, flags, config) { const chrome = await chromeLauncher.launch(CHROME_LAUNCH_OPTS); flags.port = chrome.port; try { return await lighthouse(url, flags, config); } finally { await chrome.kill(); } }
const launchChromeAndRunLighthouse = ( url, opts = { chromeFlags: ['--headless'] }, config = null ) => chromeLauncher.launch({ chromeFlags: opts.chromeFlags }).then(chrome => { opts.port = chrome.port return lighthouse(url, opts, config).then(results => chrome.kill().then(() => results.lhr) ) })
async function launchChromeAndRunLighthouse(url, opts, config = null) { return chromeLauncher.launch({ chromeFlags: opts.chromeFlags }).then((chrome) => { opts.port = chrome.port; return lighthouse(url, opts, config).then((results) => { // use results.lhr for the JS-consumeable output // https://github.com/GoogleChrome/lighthouse/blob/master/types/lhr.d.ts // use results.report for the HTML/JSON/CSV output as a string // use results.artifacts for the trace/screenshots/other specific case you need (rarer) return chrome.kill().then(() => results); }); }); }
function launchChrome() { const options = { chromeFlags: [ '--disable-gpu', '--headless', '--no-sandbox' ] }; if (process.env.REMOTE_DEBUG) { options.port = 9222; } return chromeLauncher.launch(options); }
function main() { if (args.n === 1 && !keepFirstRun) { console.log('ERROR: You are only doing one run and re-using chrome'); console.log('but did not specify --keep-first-run'); return; } console.log('Using out folder:', path.basename(outPath)); if (args.reuseChrome) { ChromeLauncher.launch().then(launcher => { return runAnalysisWithExistingChromeInstances(launcher) .catch(handleError) .then(() => launcher.kill()); }); return; } runAnalysisWithNewChromeInstances(); }
const prepareAPI = (config = {}) => { const {host = 'localhost', port = 9222, autoSelectChrome = true, headless = true} = config; const wrapperEntry = chromeLauncher.launch({ host, port, autoSelectChrome, additionalFlags: [ '--disable-gpu', headless ? '--headless' : '' ] }).then(chromeInstance => { const remoteInterface = chromeRemoteInterface(config).then(chromeAPI => chromeAPI).catch(err => { throw err; }); return Promise.all([chromeInstance, remoteInterface]) }).catch(err => { throw err }); return wrapperEntry };
async function launchChrome() { return await chromeLauncher.launch({ chromeFlags: [ "--headless", // Flags based off gulp-mocha-chrome "--no-default-browser-check", "--no-first-run", "--disable-background-timer-throttling", "--disable-default-apps", "--disable-device-discovery-notifications", "--disable-gpu", "--disable-popup-blocking", "--disable-renderer-backgrounding", "--disable-translate", // Without this flag, autoplaying audio outputs error "--autoplay-policy=no-user-gesture-required", // Without this flag, worker JS files can't be loaded "--allow-file-access-from-files" ] }); }
server.listen(port, host, async () => { const chrome = await chromeLauncher.launch({ chromeFlags: [ '--disable-gpu', '--headless', '--no-zygote', '--no-sandbox', ], }); const flags = { port: chrome.port, output: 'json', }; for (const post of posts) { console.log(`Checking "${post}"`); // eslint-disable-line no-console const result = await lighthouse(`${base}${post}`, flags, null); const report = Object.entries(result.lhr.categories).reduce((acc, [categoryName, category]) => ({ ...acc, [categoryName]: Math.round(category.score * 100), }), {}); Object.entries(TRESHOLDS).forEach(([prop, treshold]) => { if (report[prop] >= treshold) { console.log(`- "${prop}" is ${report[prop]} (>= ${treshold})`); // eslint-disable-line no-console } else { console.error(`- "${prop}" is ${report[prop]} but should be >= ${treshold}`); // eslint-disable-line no-console process.exit(1); } }); console.log(); // eslint-disable-line no-console } await chrome.kill(); await server.close(); });
(async function() { let port = argv.port; let chrome; if (!argv.port) { const chromeLauncher = require('chrome-launcher'); chrome = await chromeLauncher.launch({ chromeFlags: ['--headless', '--disable-gpu', '--remote-debugging-address=0.0.0.0'], port: 0 }); port = chrome.port; } const tab = await CDP.New({port}); const client = await CDP({tab, port}); const {Page, Network, Runtime} = client; const ONE_MB = 1024 * 1024 / 8; const throttling = { FAST_3G: { downloadThroughput: 1.6 * ONE_MB * .9, uploadThroughput: .75 * ONE_MB * .9 }, SLOW_3G: { downloadThroughput: .5 * ONE_MB * .8, uploadThroughput: .5 * ONE_MB * .8 } }; await Promise.all([ Page.enable(), Network.enable(), port && argv.throttling && Network.emulateNetworkConditions(Object.assign( {}, throttling[argv.throttling], {offline: false, latency: 10})), Network.clearBrowserCache(), Network.setCacheDisabled({cacheDisabled: true}), Network.setBypassServiceWorker({bypass: true}), ]); let loadEventPromise; Page.loadEventFired(() => { loadEventPromise(); }); const options = require(path.join(process.cwd(), argv.targets)); const perfTimings = {}; for (const [type] of options) { perfTimings[type] = []; } process.on('exit', async () => { for (const [type, timings] of Object.entries(perfTimings)) { const average = timings.reduce((a, b) => a + b) / timings.length; console.log( `Average gain for ${type} in ${timings.length} runs is ${average}`); } await CDP.Close({port, id: tab.id}); await client.close(); if (!argv.port) { await chrome.kill(); } }); for (let i = 0; i < NUMBER_OF_RUNS; i++) { for (const [type, url] of options) { requestType = type; Page.navigate({url}); await new Promise(resolve => { loadEventPromise = resolve; }); const {result: {value: perfTiming}} = await Runtime.evaluate({expression: 'window.perfTiming'}); // const {result: {value: perfTiming}} = await // Runtime.evaluate({expression: 'window.performance.timing.loadEventEnd- // window.performance.timing.navigationStart'}); perfTimings[type].push(perfTiming); } process.stdout.write(`${i + 1}/${NUMBER_OF_RUNS}\r`); } process.exit(0); })()
/*配置截图尺寸*/ const screenshotMetrics = { width: deviceMetrics.width, height: deviceMetrics.height }; /*从命令行中获取参数*/ const argv = require('minimist')(process.argv.slice(2)); const userAgent = argv.userAgent || "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"; let chrome, launcher; /*模块来调用 Chrome*/ /*是否启用 lighthouse */ chromeLauncher.launch({ port: 9222, chromeFlags: [ '--window-size=412,732', '--headless', ] }).then(Launcher => { //启用 Chrome DevTools chrome 远程控制 chromeRemoteInterface(Chrome => { const {Page, Emulation, Network, DOM, CSS,Runtime} = Chrome; Promise.all([ Page.enable(), Network.enable(), DOM.enable(), ]).then(() => { Network.setUserAgentOverride({userAgent}); Emulation.setDeviceMetricsOverride(deviceMetrics); // 配置浏览器尺寸 Emulation.setVisibleSize(screenshotMetrics); // 配置截图尺寸 Page.navigate({ url: 'https://m.medplus.net' }); })
.then(() => launch({ port: 9222, chromeFlags: [`--load-and-launch-app=${__dirname}`], enableExtensions: true }))
* chrome-debug --enable-extensions */ const {launch} = require('chrome-launcher'); const args = process.argv.slice(2); let chromeFlags; let startingUrl; let port; let enableExtensions; if (args.length) { chromeFlags = args.filter(flag => flag.startsWith('--')); const portFlag = chromeFlags.find(flag => flag.startsWith('--port=')); port = portFlag && portFlag.replace('--port=', ''); enableExtensions = !!chromeFlags.find(flag => flag === '--enable-extensions'); startingUrl = args.find(flag => !flag.startsWith('--')); } launch({ startingUrl, port, enableExtensions, chromeFlags, }) // eslint-disable-next-line no-console .then(v => console.log(`✨ Chrome debugging port: ${v.port}`));
async function launchChrome(headless) { return await chromeLauncher.launch({ chromeFlags: [headless ? '--headless' : ''], }); }
}) }) .then(image => { const buffer = new Buffer(image.data, 'base64') return new Promise((resolve, reject) => { fs.writeFile('output.jpeg', buffer, 'base64', err => { if (err) return reject(err) resolve() }) }) }) } chromeLauncher.launch({ port: 9222, chromeFlags: [ '--window-size=412,732', '--headless', '--window-size=412,732' ] }) .then(Launcher => { launcher = Launcher return new Promise((resolve, reject) =>{ chrome(Protocol => { protocol = Protocol resolve() }).on('error', err => { reject(err) }) }) }) .then(getScreenShot) .then(() => { protocol.close() launcher.kill()