Skip to main content

Service Workers

Introduction

warning

Service workers are only supported on Chromium-based browsers.

note

If you're looking to do general network mocking, routing, and interception, please see the Network Guide first. Playwright provides built-in APIs for this use case that don't require the information below. However, if you're interested in requests made by Service Workers themselves, please read below.

Service Workers provide a browser-native method of handling requests made by a page with the native Fetch API (fetch) along with other network-requested assets (like scripts, css, and images).

They can act as a network proxy between the page and the external network to perform caching logic or can provide users with an offline experience if the Service Worker adds a FetchEvent listener.

Many sites that use Service Workers simply use them as a transparent optimization technique. While users might notice a faster experience, the app's implementation is unaware of their existence. Running the app with or without Service Workers enabled appears functionally equivalent.

How to Disable Service Workers

Playwright allows to disable Service Workers during testing. This makes tests more predictable and performant. However, if your actual page uses a Service Worker, the behavior might be different.

To disable service workers, set service_workers context option to "block".

conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"service_workers": "block"
}

Accessing Service Workers and Waiting for Activation

You can use browser_context.service_workers to list the Service Workers, or specifically watch for the Service Worker if you anticipate a page will trigger its registration:

with context.expect_event("serviceworker") as worker_info:
page.goto("/example-with-a-service-worker.html")
service_worker = worker_info.value

browser_context.on("serviceworker") event is fired before the Service Worker has taken control over the page, so before evaluating in the worker with worker.evaluate() you should wait on its activation.

There are more idiomatic methods of waiting for a Service Worker to be activated, but the following is an implementation agnostic method:

page.evaluate("""async () => {
const registration = await window.navigator.serviceWorker.getRegistration();
if (registration.active?.state === 'activated')
return;
await new Promise(resolve => {
window.navigator.serviceWorker.addEventListener('controllerchange', resolve);
});
}""")

Network Events and Routing

Any network request made by the Service Worker is reported through the BrowserContext object:

Additionally, for any network request made by the Page, method response.from_service_worker return true when the request was handled a Service Worker's fetch handler.

Consider a simple service worker that fetches every request made by the page:

If index.html registers this service worker, and then fetches data.json, the following Request/Response events would be emitted (along with the corresponding network lifecycle events):

EventOwnerURLRoutedresponse.from_service_worker
browser_context.on("request")Frameindex.htmlYes
page.on("request")Frameindex.htmlYes
browser_context.on("request")Service Workertransparent-service-worker.jsYes
browser_context.on("request")Service Workerdata.jsonYes
browser_context.on("request")Framedata.jsonYes
page.on("request")Framedata.jsonYes

Since the example Service Worker just acts a basic transparent "proxy":

  • There's 2 browser_context.on("request") events for data.json; one Frame-owned, the other Service Worker-owned.
  • Only the Service Worker-owned request for the resource was routable via browser_context.route(); the Frame-owned events for data.json are not routeable, as they would not have even had the possibility to hit the external network since the Service Worker has a fetch handler registered.
caution

It's important to note: calling request.frame or response.frame will throw an exception, if called on a Request/Response that has a non-null request.service_worker.

Routing Service Worker Requests Only

def handle_route(route: Route):
if route.request.service_worker:
# NB: accessing route.request.frame here would THROW
route.fulfill(content_type="text/plain", status=200, body="from sw")
else:
route.continue_()

context.route("**", handle_route)

Known Limitations

Requests for updated Service Worker main script code currently cannot be routed (https://github.com/microsoft/playwright/issues/14711).