{"id":15012835,"url":"https://github.com/abhinaba-ghosh/playwright-lighthouse","last_synced_at":"2025-05-16T05:02:34.505Z","repository":{"id":40466070,"uuid":"272165645","full_name":"abhinaba-ghosh/playwright-lighthouse","owner":"abhinaba-ghosh","description":":performing_arts:: Playwright Lighthouse Audit","archived":false,"fork":false,"pushed_at":"2024-09-02T00:48:37.000Z","size":783,"stargazers_count":265,"open_issues_count":37,"forks_count":28,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-05-08T00:52:20.786Z","etag":null,"topics":["accessibility","best-practices","lighthouse","lighthouse-audits","performance-monitoring","playwright","pwa","seo"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/playwright-lighthouse","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/abhinaba-ghosh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"custom":["https://www.buymeacoffee.com/abhinabaghosh","https://www.paypal.com/paypalme/abhinabaghosh"]}},"created_at":"2020-06-14T08:54:14.000Z","updated_at":"2025-04-12T11:56:37.000Z","dependencies_parsed_at":"2024-01-15T19:10:18.581Z","dependency_job_id":"56f68385-b31f-440a-9541-2d398cac4cf1","html_url":"https://github.com/abhinaba-ghosh/playwright-lighthouse","commit_stats":{"total_commits":105,"total_committers":17,"mean_commits":6.176470588235294,"dds":0.7142857142857143,"last_synced_commit":"7bb21602bf60ff7f667da2567c8e5689d1e6741d"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abhinaba-ghosh%2Fplaywright-lighthouse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abhinaba-ghosh%2Fplaywright-lighthouse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abhinaba-ghosh%2Fplaywright-lighthouse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abhinaba-ghosh%2Fplaywright-lighthouse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/abhinaba-ghosh","download_url":"https://codeload.github.com/abhinaba-ghosh/playwright-lighthouse/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471028,"owners_count":22076582,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["accessibility","best-practices","lighthouse","lighthouse-audits","performance-monitoring","playwright","pwa","seo"],"created_at":"2024-09-24T19:43:18.366Z","updated_at":"2025-05-16T05:02:34.404Z","avatar_url":"https://github.com/abhinaba-ghosh.png","language":"JavaScript","funding_links":["https://www.buymeacoffee.com/abhinabaghosh","https://www.paypal.com/paypalme/abhinabaghosh"],"categories":[],"sub_categories":[],"readme":"## Lighthouse Playwright - NPM Package\n\n[![NPM release](https://img.shields.io/npm/v/playwright-lighthouse.svg 'NPM release')](https://www.npmjs.com/package/playwright-lighthouse)\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)\n[![NPM Downloads](https://img.shields.io/npm/dt/playwright-lighthouse.svg?style=flat-square)](https://www.npmjs.com/package/playwright-lighthouse)\n\n[Lighthouse](https://developers.google.com/web/tools/lighthouse) is a tool developed by Google that analyzes web apps and web pages, collecting modern performance metrics and insights on developer best practices.\n\n[Playwright](https://www.npmjs.com/package/playwright) is a Node library to automate Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.\n\nThe purpose of this package is to produce web audit report for several pages in connected mode and in an automated (programmatic) way.\n\n## Usage\n\n| `playwright-lighthouse` Version | Compatible Lighthouse Version |\n|---------------------------------|--------------------------------|\n| v3.x.x                          | 10                             |\n| v4.x.x                          | 11                             |\n\n\n### Installation\n\nAdd the `playwright-lighthouse`, `playwright` \u0026 `lighthouse` libraries to your project:\n\n```sh\n$ yarn add -D playwright-lighthouse playwright lighthouse\n# or\n$ npm install --save-dev playwright-lighthouse playwright lighthouse\n```\n\n### In your code\n\nAfter completion of the Installation, you can use `playwright-lighthouse` in your code to audit the current page.\n\nIn your test code you need to import `playwright-lighthouse` and assign a `port` for the lighthouse scan. You can choose any non-allocated port.\n\n```js\nimport { playAudit } from 'playwright-lighthouse';\nimport playwright from 'playwright';\n\ndescribe('audit example', () =\u003e {\n  it('open browser', async () =\u003e {\n    const browser = await playwright['chromium'].launch({\n      args: ['--remote-debugging-port=9222'],\n    });\n    const page = await browser.newPage();\n    await page.goto('https://angular.io/');\n\n    await playAudit({\n      page: page,\n      port: 9222,\n    });\n\n    await browser.close();\n  });\n});\n```\n\n## Thresholds per tests\n\nIf you don't provide any threshold argument to the `playAudit` command, the test will fail if at least one of your metrics is under `100`.\n\nYou can make assumptions on the different metrics by passing an object as argument to the `playAudit` command:\n\n```javascript\nimport { playAudit } from 'playwright-lighthouse';\nimport playwright from 'playwright';\n\ndescribe('audit example', () =\u003e {\n  it('open browser', async () =\u003e {\n    const browser = await playwright['chromium'].launch({\n      args: ['--remote-debugging-port=9222'],\n    });\n    const page = await browser.newPage();\n    await page.goto('https://angular.io/');\n\n    await playAudit({\n      page: page,\n      thresholds: {\n        performance: 50,\n        accessibility: 50,\n        'best-practices': 50,\n        seo: 50,\n        pwa: 50,\n      },\n      port: 9222,\n    });\n\n    await browser.close();\n  });\n});\n```\n\nIf the Lighthouse analysis returns scores that are under the one set in arguments, the test will fail.\n\nYou can also make assumptions only on certain metrics. For example, the following test will **only** verify the \"correctness\" of the `performance` metric:\n\n```javascript\nawait playAudit({\n  page: page,\n  thresholds: {\n    performance: 85,\n  },\n  port: 9222,\n});\n```\n\nThis test will fail only when the `performance` metric provided by Lighthouse will be under `85`.\n\n## Passing different Lighthouse config to playwright-lighthouse directly\n\nYou can also pass any argument directly to the Lighthouse module using the second and third options of the command:\n\n```js\nconst thresholdsConfig = {\n  /* ... */\n};\n\nconst lighthouseOptions = {\n  /* ... your lighthouse options */\n};\n\nconst lighthouseConfig = {\n  /* ... your lighthouse configs */\n};\n\nawait playAudit({\n  thresholds: thresholdsConfig,\n  opts: lighthouseOptions,\n  config: lighthouseConfig,\n\n  /* ... other configurations */\n});\n```\n\nYou can pass default lighthouse configs like so:\n\n```js\nimport lighthouseDesktopConfig from 'lighthouse/lighthouse-core/config/lr-desktop-config';\n\nawait playAudit({\n  thresholds: thresholdsConfig,\n  opts: lighthouseOptions,\n  config: lighthouseDesktopConfig,\n\n  /* ... other configurations */\n});\n```\n\nSometimes it's important to pass a parameter _disableStorageReset_ as false. You can easily make it like this:\n\n```js\nconst opts = {\n  disableStorageReset: false,\n};\n\nawait playAudit({\n  page,\n  port: 9222,\n  opts,\n});\n```\n\n## Running lighthouse on authenticated routes\n\nPlaywright by default does not share any context (eg auth state) between pages. Lighthouse will open a new page and thus any previous authentication steps are void. To persist auth state you need to use a persistent context:\n\n```js\nimport os from 'os';\nimport { playAudit } from 'playwright-lighthouse';\nimport { chromium } from 'playwright';\n\ndescribe('audit example', () =\u003e {\n  it('open browser', async () =\u003e {\n    const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random()));\n    const context = await chromium.launchPersistentContext(userDataDir, {\n      args: ['--remote-debugging-port=9222'],\n    });\n    const page = await context.newPage();\n    await page.goto('http://localhost:3000/');\n\n    // Perform login steps here which will save to cookie or localStorage\n\n    // When lighthouse opens a new page the storage will be persisted meaning the new page will have the same user session\n    await playAudit({\n      page: page,\n      port: 9222,\n    });\n\n    await context.close();\n  });\n});\n```\n\nClean up the tmp directories on playwright teardown:\n\n```ts\nimport rimraf from 'rimraf';\nimport os from 'os';\nimport path from 'path';\n\nfunction globalSetup() {\n  return () =\u003e {\n    const tmpDirPath = path.join(os.tmpdir(), 'pw');\n    rimraf(tmpDirPath, console.log);\n  };\n}\n\nexport default globalSetup;\n```\n\n## Usage with Playwright Test Runner\n\n```ts\nimport { chromium } from 'playwright';\nimport type { Browser } from 'playwright';\nimport { playAudit } from 'playwright-lighthouse';\nimport { test as base } from '@playwright/test';\nimport getPort from 'get-port';\n\nexport const lighthouseTest = base.extend\u003c\n  {},\n  { port: number; browser: Browser }\n\u003e({\n  port: [\n    async ({}, use) =\u003e {\n      // Assign a unique port for each playwright worker to support parallel tests\n      const port = await getPort();\n      await use(port);\n    },\n    { scope: 'worker' },\n  ],\n\n  browser: [\n    async ({ port }, use) =\u003e {\n      const browser = await chromium.launch({\n        args: [`--remote-debugging-port=${port}`],\n      });\n      await use(browser);\n    },\n    { scope: 'worker' },\n  ],\n});\n\nlighthouseTest.describe('Lighthouse', () =\u003e {\n  lighthouseTest('should pass lighthouse tests', async ({ page, port }) =\u003e {\n    await page.goto('http://example.com');\n    await page.waitForSelector('#some-element');\n    await playAudit({\n      page,\n      port,\n    });\n  });\n});\n```\n\n### Running lighthouse on authenticated routes with the test runner\n\n```ts\nimport os from 'os';\nimport getPort from 'get-port';\nimport { BrowserContext, chromium, Page } from 'playwright';\nimport { test as base } from '@playwright/test';\nimport { playAudit } from 'playwright-lighthouse';\n\nexport const lighthouseTest = base.extend\u003c\n  {\n    authenticatedPage: Page;\n    context: BrowserContext;\n  },\n  {\n    port: number;\n  }\n\u003e({\n  // We need to assign a unique port for each lighthouse test to allow\n  // lighthouse tests to run in parallel\n  port: [\n    async ({}, use) =\u003e {\n      const port = await getPort();\n      await use(port);\n    },\n    { scope: 'worker' },\n  ],\n\n  // As lighthouse opens a new page, and as playwright does not by default allow\n  // shared contexts, we need to explicitly create a persistent context to\n  // allow lighthouse to run behind authenticated routes.\n  context: [\n    async ({ port }, use) =\u003e {\n      const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random()));\n      const context = await chromium.launchPersistentContext(userDataDir, {\n        args: [`--remote-debugging-port=${port}`],\n      });\n      await use(context);\n      await context.close();\n    },\n    { scope: 'test' },\n  ],\n\n  authenticatedPage: [\n    async ({ context, page }, use) =\u003e {\n      // Mock any requests on the entire context\n      await context.route('https://example.com/token', (route) =\u003e {\n        return route.fulfill({\n          status: 200,\n          body: JSON.stringify({\n            // ...\n          }),\n          headers: {\n            // ...\n          },\n        });\n      });\n\n      await page.goto('http://localhost:3000');\n\n      // Setup your auth state by inserting cookies or localStorage values\n      await insertAuthState(page);\n\n      await use(page);\n    },\n    { scope: 'test' },\n  ],\n});\n\nlighthouseTest.describe('Authenticated route', () =\u003e {\n  lighthouseTest(\n    'should pass lighthouse tests',\n    async ({ port, authenticatedPage: page }) =\u003e {\n      await page.goto('http://localhost:3000/my-profile');\n      await playAudit({\n        page,\n        port,\n      });\n    }\n  );\n});\n```\n\n### Running lighthouse on authenticated routes with globalSetup\n\nIn case you have a [`globalSetup`](https://playwright.dev/docs/test-auth) script in your test you might want to reuse saved state instead of running auth before every test.  \nAdditionally, you may pass `url` instead of `page` to speedup execution and save resources.\n\n```ts\nimport os from 'os';\nimport path from 'path';\nimport { chromium, test as base } from '@playwright/test';\nimport type { BrowserContext } from '@playwright/test';\nimport getPort from 'get-port'; // version ^5.1.1 due to issues with imports in playwright 1.20.1\n\nexport const lighthouseTest = base.extend\u003c\n  { context: BrowserContext },\n  { port: number }\n\u003e({\n  port: [\n    async ({}, use) =\u003e {\n      // Assign a unique port for each playwright worker to support parallel tests\n      const port = await getPort();\n      await use(port);\n    },\n    { scope: 'worker' },\n  ],\n\n  context: [\n    async ({ port, launchOptions }, use) =\u003e {\n      const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random()));\n      const context = await chromium.launchPersistentContext(userDataDir, {\n        args: [\n          ...(launchOptions.args || []),\n          `--remote-debugging-port=${port}`,\n        ],\n      });\n\n      // apply state previously saved in the the `globalSetup`\n      await context.addCookies(require('../../state-chrome.json').cookies);\n\n      await use(context);\n      await context.close();\n    },\n    { scope: 'test' },\n  ],\n});\n\nlighthouseTest.describe('Authenticated route after globalSetup', () =\u003e {\n  lighthouseTest('should pass lighthouse tests', async ({ port }) =\u003e {\n    // it's possible to pass url directly instead of a page\n    // to avoid opening a page an extra time and keeping it opened\n    await playAudit({\n      url: 'http://localhost:3000/my-profile',\n      port,\n    });\n  });\n});\n```\n\n## Generating audit reports\n\n`playwright-lighthouse` library can produce Lighthouse CSV, HTML and JSON audit reports, that you can host in your CI server. These reports can be useful for ongoing audits and monitoring from build to build.\n\n```js\nawait playAudit({\n  /* ... other configurations */\n\n  reports: {\n    formats: {\n      json: true, //defaults to false\n      html: true, //defaults to false\n      csv: true, //defaults to false\n    },\n    name: `name-of-the-report`, //defaults to `lighthouse-${new Date().getTime()}`\n    directory: `path/to/directory`, //defaults to `${process.cwd()}/lighthouse`\n  },\n});\n```\n\nSample HTML report:\n\n![screen](./docs/lighthouse_report.png)\n\nplayAudit function also provides a promise that resolves with the Lighthouse result object containing the LHR (Lighthouse report in JSON format).\n\n```js\nconst lighthouseReport = await playAudit({\n  /* ... configurations */\n}); // lightHouse report contains the report results\n```\n\n## Generating Lighthouse reports on LambdaTest\n\nYou can execute Lighthouse reports on LambdaTest platform while executing Playwright tests with the following steps. You can generate multiple lighthouse reports in a single test.\n\n#### Install playwright-lighthouse library\n\n```sh\nnpm install playwright-lighthouse\n```\n\n#### Export the LIGTHHOUSE_LAMBDATEST environment variable to your project environment\n\n```sh\nexport LIGHTHOUSE_LAMBDATEST='true'\n```\n\n#### Sample script\n\n```js\nimport { chromium } from 'playwright';\nimport { playAudit } from 'playwright-lighthouse';\n\n(async () =\u003e {\n  let browser, page;\n  try {\n    const capabilities = {\n      browserName: 'Chrome', // Browsers allowed: `Chrome`, `MicrosoftEdge` and `pw-chromium`\n      browserVersion: 'latest',\n      'LT:Options': {\n        platform: 'Windows 11',\n        build: 'Web Performance testing',\n        name: 'Lighthouse test',\n        user: process.env.LT_USERNAME,\n        accessKey: process.env.LT_ACCESS_KEY,\n        network: true,\n        video: true,\n        console: true,\n      },\n    };\n\n    browser = await chromium.connect({\n      wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`,\n    });\n\n    page = await browser.newPage();\n\n    await page.goto('https://duckduckgo.com');\n    let element = await page.locator('[name=\"q\"]');\n    await element.click();\n    await element.type('Playwright');\n    await element.press('Enter');\n\n    try {\n      await playAudit({\n        url: 'https://duckduckgo.com',\n        page: page,\n        thresholds: {\n          performance: 50,\n          accessibility: 50,\n          'best-practices': 50,\n          seo: 50,\n          pwa: 10,\n        },\n        reports: {\n          formats: {\n            json: true,\n            html: true,\n            csv: true,\n          },\n        },\n      });\n\n      await page.evaluate(\n        (_) =\u003e {},\n        `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'passed', remark: 'Web performance metrics are are above the thresholds.' } })}`\n      );\n    } catch (e) {\n      await page.evaluate(\n        (_) =\u003e {},\n        `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: e.stack } })}`\n      );\n      console.error(e);\n    }\n  } catch (e) {\n    await page.evaluate(\n      (_) =\u003e {},\n      `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: e.stack } })}`\n    );\n  } finally {\n    await page.close();\n    await browser.close();\n  }\n})();\n```\n\n#### Viewing test results\n\nYou can view your tests on [LambdaTest Web Automation dashboard](https://automation.lambdatest.com).\n\n![Lighthouse report on LambdaTest](./docs/LambdaTest_Playwright_LighthouseReport.png)\n\n## Tell me your issues\n\nyou can raise any issue [here](https://github.com/abhinaba-ghosh/playwright-lighthouse/issues)\n\n## Before you go\n\nIf it works for you , give a [Star](https://github.com/abhinaba-ghosh/playwright-lighthouse)! :star:\n\n_- Copyright \u0026copy; 2020- [Abhinaba Ghosh](https://www.linkedin.com/in/abhinaba-ghosh-9a2ab8a0/)_\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabhinaba-ghosh%2Fplaywright-lighthouse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fabhinaba-ghosh%2Fplaywright-lighthouse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabhinaba-ghosh%2Fplaywright-lighthouse/lists"}