Block Analytics and Ads in Playwright Tests

Originally Published: July 28, 2024

I use Google Analytics, Microsoft Clarity, and/or Google Adsense on some sites. I also have integration tests using Playwright in these projects. I don’t want these tests to be counted in my analytics or ad impressions. Here’s how I block these services in my Playwright tests.

With the help of Playwright documentation, I wrote some code in a beforeEach hook to abort all requests to the following domains:

test.beforeEach(async ({ context }) => {
  await context.route('**/*', request => {
    const url = request.request().url()
    if (
      // Google Analytics
      url.startsWith('https://www.googletagmanager.com') ||
      // Microsoft Clarity
      url.startsWith('https://www.clarity.ms') ||
      // Google Adsense
      url.startsWith('https://pagead2.googlesyndication.com')
    ) {
      request.abort()
    } else {
      request.continue()
    }
  })
})

Make sure you carefully check that your analytics or ad code uses these domains. You might want to block additional domains based on your setup.