Skip to content

fix(chromium): emit serviceworker event on MV3 SW stop/restart lifecycle#39476

Open
shairoth12 wants to merge 5 commits intomicrosoft:mainfrom
shairoth12:fix-service-worker-issue
Open

fix(chromium): emit serviceworker event on MV3 SW stop/restart lifecycle#39476
shairoth12 wants to merge 5 commits intomicrosoft:mainfrom
shairoth12:fix-service-worker-issue

Conversation

@shairoth12
Copy link

Fixes #39475

Problem

When a Manifest V3 extension's service worker stops and restarts, Chrome reuses the same CDP target ID. This means no Target.attachedToTarget event is fired, so Playwright never creates a new CRServiceWorker instance and the 'serviceworker' event is never emitted on the BrowserContext. The original Worker reference remains in context.serviceWorkers() with a stale execution context, causing any subsequent evaluate() to throw.

Fix

Restart detection is now handled at the execution-context level inside CRServiceWorker, which already holds the CDP session for the reused target.

Two new fields track the current context lifecycle:

  • _currentContextId — the execution context ID currently in use
  • _currentContextDestroyed — set to true by Runtime.executionContextDestroyed or Runtime.executionContextsCleared

The Runtime.executionContextCreated listener (previously session.once) is now persistent. When a new context arrives after the previous one was destroyed, _handleRestart() is called:

  1. The old Worker is retired (emits Worker.Events.Close, closes its scope, removes it from browser._serviceWorkers) — without disposing the CDP session, since the new worker reuses it
  2. A fresh CRServiceWorker is created with the same session and target ID
  3. The 'serviceworker' event is emitted on the BrowserContext

A same-ID re-send from Runtime.enable (context still alive) is correctly ignored via the _currentContextDestroyed flag.

Changes

  • packages/playwright-core/src/server/chromium/crServiceWorker.ts — restart detection and handling
  • packages/playwright-core/src/server/chromium/crBrowser.ts — pass targetId to CRServiceWorker constructor
  • tests/library/chromium/extensions.spec.ts — new test for stop/restart lifecycle; timing fix to register waitForEvent before triggering the cycle
  • docs/src/chrome-extensions-js-python.md — new "Testing extension reload" section
  • docs/src/api/class-browsercontext.md — updated serviceworker event docs with timing guidance

@shairoth12
Copy link
Author

@microsoft-github-policy-service agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: serviceworker event never emitted when a Manifest V3 extension's service worker stops and restarts

1 participant