Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix(chromium): handle MV3 service worker restart (#39476)
Shai Roth19b3ac770080
diff --git a/docs/src/chrome-extensions-js-python.md b/docs/src/chrome-extensions-js-python.mdindex 9512a0acf8..1475ffb22f 100644--- a/docs/src/chrome-extensions-js-python.md+++ b/docs/src/chrome-extensions-js-python.md@@ -101,6 +101,45 @@ with sync_playwright() as playwright:run(playwright)```+## Service worker idle suspension (MV3)++Chrome MV3 service workers are automatically suspended after ~30 seconds of inactivity and restarted+on demand. When this happens, Playwright keeps the **same [Worker] object alive** — no new+`'serviceworker'` event is emitted. New `evaluate()` calls issued during the restart window are+stalled until the new context is ready and then resume automatically:++```js+const sw = await context.waitForEvent('serviceworker');++// ... SW suspends after 30 s of inactivity and is restarted by the browser ...++// The existing handle is transparent across the restart.+await sw.evaluate(() => sendMessage({ type: 'ping' })); // just works+```++```python async+sw = await context.wait_for_event('serviceworker')++# ... SW suspends after 30 s of inactivity and is restarted by the browser ...++# The existing handle is transparent across the restart.+await sw.evaluate("sendMessage({ type: 'ping' })") # just works+```++```python sync+sw = context.wait_for_event('serviceworker')++# ... SW suspends after 30 s of inactivity and is restarted by the browser ...++# The existing handle is transparent across the restart.+sw.evaluate("sendMessage({ type: 'ping' })") # just works+```++:::note+`evaluate()` calls that were already in-flight at the exact moment of suspension will throw+with `"Service worker restarted"`, matching the behaviour of page navigations mid-flight.+:::+## TestingTo have the extension loaded when running tests you can use a test fixture to set the context. You can also dynamically retrieve the extension id and use it to load and test the popup page for example.diff --git a/packages/playwright-core/src/server/chromium/crServiceWorker.ts b/packages/playwright-core/src/server/chromium/crServiceWorker.tsindex 31d0ded84e..b49bf0748c 100644--- a/packages/playwright-core/src/server/chromium/crServiceWorker.ts+++ b/packages/playwright-core/src/server/chromium/crServiceWorker.ts@@ -23,6 +23,7 @@ import { toConsoleMessageLocation } from './crProtocolHelper';import type { CRBrowserContext } from './crBrowser';import type { CRSession } from './crConnection';+import type { Protocol } from './protocol';export class CRServiceWorker extends Worker {readonly browserContext: CRBrowserContext;@@ -35,13 +36,17 @@ export class CRServiceWorker extends Worker {this.browserContext = browserContext;if (!process.env.PLAYWRIGHT_DISABLE_SERVICE_WORKER_NETWORK)this._networkManager = new CRNetworkManager(null, this);- session.once('Runtime.executionContextCreated', event => {++ session.on('Inspector.targetCrashed', () => this._prepareContextForRestart());++ session.on('Runtime.executionContextCreated', (event: Protocol.Runtime.executionContextCreatedPayload) => {this.createExecutionContext(new CRExecutionContext(session, event.context));+ if (this.browserContext._browser.majorVersion() < 143)+ this.workerScriptLoaded();});+if (this.browserContext._browser.majorVersion() >= 143)session.on('Inspector.workerScriptLoaded', () => this.workerScriptLoaded());- else- this.workerScriptLoaded();if (this._networkManager && this._isNetworkInspectionEnabled()) {this.updateRequestInterception();@@ -59,8 +64,8 @@ export class CRServiceWorker extends Worker {this.browserContext.emit(BrowserContext.Events.Console, message);});- session.send('Runtime.enable', {}).catch(e => { });- session.send('Runtime.runIfWaitingForDebugger').catch(e => { });+ session.send('Runtime.enable', {}).catch(e => {});+ session.send('Runtime.runIfWaitingForDebugger').catch(e => {});session.on('Inspector.targetReloadedAfterCrash', () => {// Resume service worker after restart.session._sendMayFail('Runtime.runIfWaitingForDebugger', {});diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.tsindex 95cd244ebb..8b3de659e5 100644--- a/packages/playwright-core/src/server/page.ts+++ b/packages/playwright-core/src/server/page.ts@@ -915,6 +915,16 @@ export class Worker extends SdkObject<WorkerEventMap> {this._executionContextPromise.resolve(this.existingExecutionContext);}+ protected _prepareContextForRestart() {+ if (this.existingExecutionContext)+ this.existingExecutionContext.contextDestroyed('Service worker restarted');+ this.existingExecutionContext = null;+ // Reset so createExecutionContext() waits for workerScriptLoaded() before resolving —+ // mirroring initial startup and ensuring the script has run before evaluations proceed.+ this._workerScriptLoaded = false;+ this._executionContextPromise = new ManualPromise<js.ExecutionContext>();+ }+didClose() {if (this.existingExecutionContext)this.existingExecutionContext.contextDestroyed('Worker was closed');diff --git a/tests/assets/extension-mv3-sw-lifecycle/background.js b/tests/assets/extension-mv3-sw-lifecycle/background.jsnew file mode 100644index 0000000000..4914caadec--- /dev/null+++ b/tests/assets/extension-mv3-sw-lifecycle/background.js@@ -0,0 +1,2 @@+// Each time the service worker starts (or restarts), this runs fresh.+globalThis.startTime = Date.now();diff --git a/tests/assets/extension-mv3-sw-lifecycle/manifest.json b/tests/assets/extension-mv3-sw-lifecycle/manifest.jsonnew file mode 100644index 0000000000..ad6a4ed645--- /dev/null+++ b/tests/assets/extension-mv3-sw-lifecycle/manifest.json@@ -0,0 +1,8 @@+{+ "name": "SW Lifecycle Test Extension",+ "version": "0.1",+ "background": {+ "service_worker": "background.js"+ },+ "manifest_version": 3+}diff --git a/tests/library/chromium/extensions.spec.ts b/tests/library/chromium/extensions.spec.tsindex e7d48030df..f1015763ed 100644--- a/tests/library/chromium/extensions.spec.ts+++ b/tests/library/chromium/extensions.spec.ts@@ -42,6 +42,50 @@ it.skip(({ isHeadlessShell }) => isHeadlessShell, 'Headless Shell has no supportit.describe('MV3', () => {it.skip(({ channel }) => channel?.startsWith('chrome'), '--load-extension is not supported in Chrome anymore. https://groups.google.com/a/chromium.org/g/chromium-extensions/c/1-g8EFx2BBY/m/S0ET5wPjCAAJ');+ it('should support service worker stop and restart lifecycle', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/39475' }+ }, async ({ launchPersistentContext, asset }) => {+ const extensionPath = asset('extension-mv3-sw-lifecycle');+ const context = await launchPersistentContext(extensionPath);++ const serviceWorkers = context.serviceWorkers();+ const sw1 = serviceWorkers.length ? serviceWorkers[0] : await context.waitForEvent('serviceworker');+ const startTime1 = await sw1.evaluate(() => (globalThis as any).startTime);++ // stopWorker keeps the same CDP target alive, matching Chrome's natural idle suspension behavior.+ const page = await context.newPage();+ const cdp = await context.newCDPSession(page);++ let versionId: string | undefined;+ let scopeURL: string | undefined;+ let runningStatus: string | undefined;+ cdp.on('ServiceWorker.workerVersionUpdated', ({ versions }: any) => {+ const v = versions[0];+ if (!v)+ return;+ versionId = v.versionId;+ runningStatus = v.runningStatus;+ });+ cdp.on('ServiceWorker.workerRegistrationUpdated', ({ registrations }: any) => {+ if (registrations.length)+ scopeURL = registrations[0].scopeURL;+ });+ await cdp.send('ServiceWorker.enable');+ await expect.poll(() => versionId && scopeURL, { timeout: 5000 }).toBeTruthy();++ await cdp.send('ServiceWorker.stopWorker', { versionId });+ // Wait for full stop before triggering restart.+ await expect.poll(() => runningStatus, { timeout: 5000 }).toBe('stopped');+ await cdp.send('ServiceWorker.startWorker', { scopeURL });+ await expect.poll(() => runningStatus, { timeout: 5000 }).toBe('running');++ const startTime2 = await sw1.evaluate(() => (globalThis as any).startTime);+ expect(startTime2).toBeGreaterThan(startTime1);+ expect(context.serviceWorkers()).toStrictEqual([sw1]); // same object, no new event++ await context.close();+ });+it('should give access to the service worker', async ({ launchPersistentContext, asset }) => {const extensionPath = asset('extension-mv3-simple');const context = await launchPersistentContext(extensionPath);