Skip to content

Service Worker Chaos

Service Worker fetches run outside the page. Page-side fetch and XMLHttpRequest patches cannot see them, so Chaos Maker ships a small @chaos-maker/core/sw bundle plus adapter helpers that send config to the active worker.

Classic workers can load the IIFE bundle with importScripts.

sw.js
importScripts('/chaos-maker-sw.js');

Module workers can import the subpath directly.

sw-module.js
import { installChaosSW } from '@chaos-maker/core/sw';
installChaosSW({ source: 'message' });

Serve node_modules/@chaos-maker/core/dist/sw.js or sw.mjs from a URL inside the worker scope. The page-side helpers validate config, wait for a controller, send it over postMessage, and return only after the worker acknowledges it.

import { injectSWChaos, getSWChaosLog, removeSWChaos } from '@chaos-maker/playwright';
await page.goto('/app-with-sw/');
await page.waitForFunction(() => !!navigator.serviceWorker.controller);
await injectSWChaos(page, {
seed: 42,
network: { failures: [{ urlPattern: '/api/data', statusCode: 503, probability: 1 }] },
});
await page.click('#refresh');
const log = await getSWChaosLog(page);
expect(log.some((event) => event.type === 'network:failure' && event.applied)).toBe(true);
await removeSWChaos(page);

getSWChaosLog() reads events buffered in the page. getSWChaosLogFromSW() asks the worker for its in-memory log and is useful when debugging a race where the page listener missed an early broadcast.

The bridge reapplies the last config after controllerchange, so an updated worker keeps the same chaos settings once it controls the page.

  • caches.match() hits bypass self.fetch, so cached responses are not intercepted in v0.4.0.
  • Push and background sync events are outside this release.
  • Cross-origin workers for third-party widgets are not supported.