Search code examples
javascriptpuppeteerlighthouse

Browser instance get killed while running light house through puppeteer on the second page


On my application I am running light house on various page in my application, in an orderly manner for example first on the launch page then again once I log in one more time and so on.

So after launch page and when I am trying to go for the authentication the browser instance is getting killed. I am also retrieving the page metrics and windows metrics. Here below is my code,

(async () => {
    const launchOptions = {
        headless: false,
        executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
        args: ['--start-maximized',
            '--disable-web-security',
            '--disable-features=IsolateOrigins,site-per-process'],
        defaultViewport: null
    };
    const lightHouseopts = {
        logLevel: 'info',
        output: 'json',
        disableDeviceEmulation: false,
        defaultViewport: {
            width: 1200,
            height: 900
        },
        chromeFlags: ['--disable-mobile-emulation']
    };
    const browser = await puppeteer.launch(launchOptions);
    const url = "";
    const page = await browser.newPage();
    try {
        await page.goto(url);
        const metrics = await page.metrics();
        await influx.write([{
            measurement: 'launch_page_puppeteer_evaluation',
            tags: {
                page: 'launchpagepuppeteer'
            },
            fields: metrics
        }])

        const performanceTiming = JSON.parse(
            await page.evaluate(() => JSON.stringify(window.performance.timing))
        );

        performanceWindowsMetrics(performanceTiming, 'launchpagewindowsperformance', 'launch_page_windows_performance')
        const configLightHouse = null;
        const chrome = await chromeLauncher.launch(lightHouseopts);
        lightHouseopts.port = chrome.port;

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

        // Run Lighthouse
        const { lhr } = await lighthouse(page.url(), lightHouseopts, configLightHouse);
        await browser.disconnect();
        await chrome.kill();

        const json = reportGenerator.generateReport(lhr, 'json');
        const audits = JSON.parse(json).audits; // Lighthouse audits
        const first_contentful_paint = audits['first-contentful-paint'].displayValue;
        const total_blocking_time = audits['total-blocking-time'].displayValue;
        const time_to_interactive = audits['interactive'].displayValue;

        console.log(`\n
        Lighthouse metrics: 
        🎨 First Contentful Paint: ${first_contentful_paint}, 
        ⌛️ Total Blocking Time: ${total_blocking_time},
        👆 Time To Interactive: ${time_to_interactive}`);

        const time = new Date().getTime();
        const html = reportGenerator.generateReport(lhr, 'html');
        fs.writeFile(`report-${time}.html`, html, function (err) {
            if (err) throw err;
        });
        await userNamePage.enterUserName(page, inputFiles.mySiteUserName);
        await passwordPage.enterPassword(page, inputFiles.mySitPassword);
        await page.waitFor(500);


        await browser.disconnect();
        await chrome.kill();
    } catch (error) {
        console.error(error);
    } finally {

        await page.waitFor(10000);
        console.log("Closing the browser session")
        await browser.close();
    }
})();

Getting broswer instance killed.

enter image description here enter image description here enter image description here


Solution

  • I figure it out by some research, thought I can help the community if someone same searching for the answer.

    First the root cause that cause the browser getting killed, by default Light House is not responsible for keeping the session, it run on the session maintained by the browser. That why when LightHouse triggered from Puppeteer, the session is maintained by Puppeteer not the browser used by the Puppeteer.

    Solution: You need to copy the session token or id from the Puppeteer and pass it on to Google Light House when it is called, you can put it in the argument list.

    Inside the blow code:

    const lightHouseopts = {
            logLevel: 'info',
            output: 'json',
            disableDeviceEmulation: false,
            defaultViewport: {
                width: 1200,
                height: 900
            },
            chromeFlags: ['--disable-mobile-emulation']
        };