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(reuse): clear cookies and local storage when reusing context (#16175)
Pavel Feldmand5bc5ee6f74f
diff --git a/examples/todomvc/tests/integration.spec.ts b/examples/todomvc/tests/integration.spec.tsindex 58a99b87af..47778cd765 100644--- a/examples/todomvc/tests/integration.spec.ts+++ b/examples/todomvc/tests/integration.spec.ts@@ -233,7 +233,6 @@ test.describe('Editing', () => {await todoItems.nth(1).locator('.edit').fill('');await todoItems.nth(1).locator('.edit').press('Enter');- await page.pause();await expect(todoItems).toHaveText([TODO_ITEMS[0],TODO_ITEMS[2],diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex 0c92f95fa4..b5d9efde83 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -170,6 +170,9 @@ export abstract class BrowserContext extends SdkObject {// Unless I do this early, setting extra http headers below does not respond.await page?._frameManager.closeOpenDialogs();+ // This should be before the navigation to about:blank so that we could save on+ // a navigation as we clear local storage.+ await this._clearLocalStorage();await page?.mainFrame().goto(metadata, 'about:blank', { timeout: 0 });await this._removeExposedBindings();await this._removeInitScripts();@@ -181,6 +184,7 @@ export abstract class BrowserContext extends SdkObject {await this.setExtraHTTPHeaders(this._options.extraHTTPHeaders || []);await this.setGeolocation(this._options.geolocation);await this.setOffline(!!this._options.offline);+ await this.clearCookies();await page?.resetForReuse(metadata);}@@ -457,6 +461,32 @@ export abstract class BrowserContext extends SdkObject {return result;}+ async _clearLocalStorage() {+ if (!this._origins.size)+ return;+ let page = this.pages()[0];+ const originArray = [...this._origins];++ // Fast path.+ if (page && originArray.length === 1 && page.mainFrame().url().startsWith(originArray[0])) {+ await page.mainFrame().evaluateExpression(`localStorage.clear()`, false, undefined, 'utility');+ return;+ }++ // Slow path.+ const internalMetadata = serverSideCallMetadata();+ page = page || await this.newPage(internalMetadata);+ await page._setServerRequestInterceptor(handler => {+ handler.fulfill({ body: '<html></html>' }).catch(() => {});+ });+ for (const origin of this._origins) {+ const frame = page.mainFrame();+ await frame.goto(internalMetadata, origin);+ await frame.evaluateExpression(`localStorage.clear()`, false, undefined, 'utility');+ }+ await page._setServerRequestInterceptor(undefined);+ }+isSettingStorageState(): boolean {return this._settingStorageState;}