Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat: BrowserContext.setStorageState (#36875)

Dmitry Gozmand733e92095ab
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index aa98489296..d822d9aa50 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -1495,6 +1495,29 @@ its geolocation.
Whether to emulate network being offline for the browser context.
+
+## async method: BrowserContext.setStorageState
+* since: v1.55
+
+Resets storage state in the context by clearing cookies, cache and storage, and then applying the new storage state.
+
+### param: BrowserContext.setStorageState.storageState = %%-js-python-context-option-storage-state-%%
+* since: v1.55
+
+### param: BrowserContext.setStorageState.storageState = %%-csharp-java-context-option-storage-state-%%
+* since: v1.55
+
+
+## async method: BrowserContext.setStorageStatePath
+* since: v1.55
+* langs: csharp, java
+
+Resets storage state in the context by clearing cookies, cache and storage, and then applying the new storage state from a file.
+
+### param: BrowserContext.setStorageStatePath.storageStatePath = %%-csharp-java-context-option-storage-state-path-%%
+* since: v1.55
+
+
## async method: BrowserContext.storageState
* since: v1.8
- returns: <[Object]>
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 01cc047648..a72dc2a485 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -9273,6 +9273,64 @@ export interface BrowserContext {
*/
setOffline(offline: boolean): Promise<void>;
+ /**
+ * Resets storage state in the context by clearing cookies, cache and storage, and then applying the new storage
+ * state.
+ * @param storageState Learn more about [storage state and auth](https://playwright.dev/docs/auth).
+ *
+ * Populates context with given storage state. This option can be used to initialize context with logged-in
+ * information obtained via
+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state).
+ */
+ setStorageState(storageState: string|{
+ /**
+ * Cookies to set for context
+ */
+ cookies: Array<{
+ name: string;
+
+ value: string;
+
+ /**
+ * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
+ * this: ".example.com"
+ */
+ domain: string;
+
+ /**
+ * Domain and path are required
+ */
+ path: string;
+
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
+
+ httpOnly: boolean;
+
+ secure: boolean;
+
+ /**
+ * sameSite flag
+ */
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
+
+ origins: Array<{
+ origin: string;
+
+ /**
+ * localStorage to set for context
+ */
+ localStorage: Array<{
+ name: string;
+
+ value: string;
+ }>;
+ }>;
+ }): Promise<void>;
+
/**
* Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
* snapshot.
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts
index 1d177df991..5a1bad8987 100644
--- a/packages/playwright-core/src/client/browserContext.ts
+++ b/packages/playwright-core/src/client/browserContext.ts
@@ -41,7 +41,7 @@ import { urlMatchesEqual } from '../utils/isomorphic/urlMatch';
import { isRegExp, isString } from '../utils/isomorphic/rtti';
import { rewriteErrorMessage } from '../utils/isomorphic/stackTrace';
-import type { BrowserContextOptions, Headers, StorageState, WaitForEventOptions } from './types';
+import type { BrowserContextOptions, Headers, SetStorageState, StorageState, WaitForEventOptions } from './types';
import type * as structs from '../../types/structs';
import type * as api from '../../types/types';
import type { URLMatch } from '../utils/isomorphic/urlMatch';
@@ -455,6 +455,10 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
return state;
}
+ async setStorageState(storageState: string | SetStorageState) {
+ await this._channel.setStorageState({ storageState: await prepareStorageState(this._platform, storageState) });
+ }
+
backgroundPages(): Page[] {
return [...this._backgroundPages];
}
@@ -527,13 +531,13 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
}
}
-async function prepareStorageState(platform: Platform, options: BrowserContextOptions): Promise<channels.BrowserNewContextParams['storageState']> {
- if (typeof options.storageState !== 'string')
- return options.storageState as any;
+async function prepareStorageState(platform: Platform, storageState: string | SetStorageState): Promise<NonNullable<channels.BrowserNewContextParams['storageState']>> {
+ if (typeof storageState !== 'string')
+ return storageState as any;
try {
- return JSON.parse(await platform.fs().promises.readFile(options.storageState, 'utf8'));
+ return JSON.parse(await platform.fs().promises.readFile(storageState, 'utf8'));
} catch (e) {
- rewriteErrorMessage(e, `Error reading storage state from ${options.storageState}:\n` + e.message);
+ rewriteErrorMessage(e, `Error reading storage state from ${storageState}:\n` + e.message);
throw e;
}
}
@@ -548,7 +552,7 @@ export async function prepareBrowserContextParams(platform: Platform, options: B
viewport: options.viewport === null ? undefined : options.viewport,
noDefaultViewport: options.viewport === null,
extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
- storageState: await prepareStorageState(platform, options),
+ storageState: options.storageState ? await prepareStorageState(platform, options.storageState) : undefined,
serviceWorkers: options.serviceWorkers,
colorScheme: options.colorScheme === null ? 'no-override' : options.colorScheme,
reducedMotion: options.reducedMotion === null ? 'no-override' : options.reducedMotion,
diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.ts
index f9174d120d..77a60cc858 100644
--- a/packages/playwright-core/src/protocol/validator.ts
+++ b/packages/playwright-core/src/protocol/validator.ts
@@ -1071,6 +1071,13 @@ scheme.BrowserContextStorageStateResult = tObject({
cookies: tArray(tType('NetworkCookie')),
origins: tArray(tType('OriginStorage')),
});
+scheme.BrowserContextSetStorageStateParams = tObject({
+ storageState: tObject({
+ cookies: tOptional(tArray(tType('SetNetworkCookie'))),
+ origins: tOptional(tArray(tType('SetOriginStorage'))),
+ }),
+});
+scheme.BrowserContextSetStorageStateResult = tOptional(tObject({}));
scheme.BrowserContextPauseParams = tOptional(tObject({}));
scheme.BrowserContextPauseResult = tOptional(tObject({}));
scheme.BrowserContextEnableRecorderParams = tObject({
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts
index 3ae466f74b..d91f2f9668 100644
--- a/packages/playwright-core/src/server/browserContext.ts
+++ b/packages/playwright-core/src/server/browserContext.ts
@@ -213,7 +213,7 @@ export abstract class BrowserContext extends SdkObject {
await progress.race(this.setUserAgent(this._options.userAgent));
await progress.race(this.doUpdateDefaultEmulatedMedia());
await progress.race(this.doUpdateDefaultViewport());
- await this.setStorageState(progress, this._options.storageState, 'reset');
+ await this.setStorageState(progress, this._options.storageState, 'resetForReuse');
await page?.resetForReuse(progress);
}
@@ -612,11 +612,11 @@ export abstract class BrowserContext extends SdkObject {
return this._creatingStorageStatePage;
}
- async setStorageState(progress: Progress, state: channels.BrowserNewContextParams['storageState'], mode: 'initial' | 'reset') {
+ async setStorageState(progress: Progress, state: channels.BrowserNewContextParams['storageState'], mode: 'initial' | 'resetForReuse' | 'update') {
let page: Page | undefined;
let interceptor: network.RouteHandler | undefined;
try {
- if (mode === 'reset') {
+ if (mode !== 'initial') {
await progress.race(this.clearCache());
await progress.race(this.doClearCookies());
}
@@ -627,11 +627,11 @@ export abstract class BrowserContext extends SdkObject {
const newOrigins = new Map(state?.origins?.map(p => [p.origin, p]) || []);
const allOrigins = new Set([...this._origins, ...newOrigins.keys()]);
if (allOrigins.size) {
- if (mode === 'reset')
+ if (mode === 'resetForReuse')
page = this.pages()[0];
if (!page) {
try {
- this._creatingStorageStatePage = mode === 'initial';
+ this._creatingStorageStatePage = mode !== 'resetForReuse';
page = await this.newPage(progress, this._creatingStorageStatePage);
} finally {
this._creatingStorageStatePage = false;
@@ -660,7 +660,7 @@ export abstract class BrowserContext extends SdkObject {
rewriteErrorMessage(error, `Error setting storage state:\n` + error.message);
throw error;
} finally {
- if (mode === 'initial')
+ if (mode !== 'resetForReuse')
await page?.close();
else if (interceptor)
await page?.removeRequestInterceptor(interceptor);
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index 15c8f84fd0..6803d00e52 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -330,6 +330,10 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
return await progress.race(this._context.storageState(progress, params.indexedDB));
}
+ async setStorageState(params: channels.BrowserContextSetStorageStateParams, progress: Progress): Promise<channels.BrowserContextSetStorageStateResult> {
+ await this._context.setStorageState(progress, params.storageState, 'update');
+ }
+
async close(params: channels.BrowserContextCloseParams, progress: Progress): Promise<void> {
progress.metadata.potentiallyClosesScope = true;
await this._context.close(params);
diff --git a/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts b/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
index 87121b0bed..c85f04c599 100644
--- a/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
+++ b/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
@@ -82,6 +82,7 @@ export const methodMetainfo = new Map<string, { internal?: boolean, title?: stri
['BrowserContext.setWebSocketInterceptionPatterns', { internal: true, }],
['BrowserContext.setOffline', { title: 'Set offline mode', }],
['BrowserContext.storageState', { title: 'Get storage state', }],
+ ['BrowserContext.setStorageState', { title: 'Set storage state', }],
['BrowserContext.pause', { title: 'Pause', }],
['BrowserContext.enableRecorder', { internal: true, }],
['BrowserContext.disableRecorder', { internal: true, }],
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 01cc047648..a72dc2a485 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -9273,6 +9273,64 @@ export interface BrowserContext {
*/
setOffline(offline: boolean): Promise<void>;
+ /**
+ * Resets storage state in the context by clearing cookies, cache and storage, and then applying the new storage
+ * state.
+ * @param storageState Learn more about [storage state and auth](https://playwright.dev/docs/auth).
+ *
+ * Populates context with given storage state. This option can be used to initialize context with logged-in
+ * information obtained via
+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state).
+ */
+ setStorageState(storageState: string|{
+ /**
+ * Cookies to set for context
+ */
+ cookies: Array<{
+ name: string;
+
+ value: string;
+
+ /**
+ * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
+ * this: ".example.com"
+ */
+ domain: string;
+
+ /**
+ * Domain and path are required
+ */
+ path: string;
+
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
+
+ httpOnly: boolean;
+
+ secure: boolean;
+
+ /**
+ * sameSite flag
+ */
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
+
+ origins: Array<{
+ origin: string;
+
+ /**
+ * localStorage to set for context
+ */
+ localStorage: Array<{
+ name: string;
+
+ value: string;
+ }>;
+ }>;
+ }): Promise<void>;
+
/**
* Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB
* snapshot.
diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.ts
index 33fce000bf..f753e28255 100644
--- a/packages/protocol/src/channels.d.ts
+++ b/packages/protocol/src/channels.d.ts
@@ -1612,6 +1612,7 @@ export interface BrowserContextChannel extends BrowserContextEventTarget, EventT
setWebSocketInterceptionPatterns(params: BrowserContextSetWebSocketInterceptionPatternsParams, progress?: Progress): Promise<BrowserContextSetWebSocketInterceptionPatternsResult>;
setOffline(params: BrowserContextSetOfflineParams, progress?: Progress): Promise<BrowserContextSetOfflineResult>;
storageState(params: BrowserContextStorageStateParams, progress?: Progress): Promise<BrowserContextStorageStateResult>;
+ setStorageState(params: BrowserContextSetStorageStateParams, progress?: Progress): Promise<BrowserContextSetStorageStateResult>;
pause(params?: BrowserContextPauseParams, progress?: Progress): Promise<BrowserContextPauseResult>;
enableRecorder(params: BrowserContextEnableRecorderParams, progress?: Progress): Promise<BrowserContextEnableRecorderResult>;
disableRecorder(params?: BrowserContextDisableRecorderParams, progress?: Progress): Promise<BrowserContextDisableRecorderResult>;
@@ -1862,6 +1863,16 @@ export type BrowserContextStorageStateResult = {
cookies: NetworkCookie[],
origins: OriginStorage[],
};
+export type BrowserContextSetStorageStateParams = {
+ storageState: {
+ cookies?: SetNetworkCookie[],
+ origins?: SetOriginStorage[],
+ },
+};
+export type BrowserContextSetStorageStateOptions = {
+
+};
+export type BrowserContextSetStorageStateResult = void;
export type BrowserContextPauseParams = {};
export type BrowserContextPauseOptions = {};
export type BrowserContextPauseResult = void;
diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.yml
index b24db0f39d..ab25ad6050 100644
--- a/packages/protocol/src/protocol.yml
+++ b/packages/protocol/src/protocol.yml
@@ -1327,6 +1327,19 @@ BrowserContext:
type: array
items: OriginStorage
+ setStorageState:
+ title: Set storage state
+ parameters:
+ storageState:
+ type: object
+ properties:
+ cookies:
+ type: array?
+ items: SetNetworkCookie
+ origins:
+ type: array?
+ items: SetOriginStorage
+
pause:
title: Pause
diff --git a/tests/library/browsercontext-storage-state.spec.ts b/tests/library/browsercontext-storage-state.spec.ts
index 4f4fca6cee..8c11a08695 100644
--- a/tests/library/browsercontext-storage-state.spec.ts
+++ b/tests/library/browsercontext-storage-state.spec.ts
@@ -500,3 +500,74 @@ it('should support empty indexedDB', { annotation: { type: 'issue', description:
const context = await contextFactory({ storageState });
expect(await context.storageState({ indexedDB: true })).toEqual(storageState);
});
+
+it('should cleanup existing and set new storage state', async ({ contextFactory }, testInfo) => {
+ const context = await contextFactory();
+ const page = await context.newPage();
+ await page.route('**/*', route => {
+ route.fulfill({ body: '<html></html>' }).catch(() => {});
+ });
+ await page.goto('https://www.example.com');
+ await page.evaluate(async () => {
+ localStorage['name1'] = 'value1';
+ document.cookie = 'username=John Doe';
+ return document.cookie;
+ });
+
+ const state = await context.storageState();
+ expect(state).toEqual({
+ cookies: [
+ expect.objectContaining({
+ domain: 'www.example.com',
+ name: 'username',
+ value: 'John Doe',
+ }),
+ ],
+ origins: [
+ {
+ origin: 'https://www.example.com',
+ localStorage: [{
+ name: 'name1',
+ value: 'value1',
+ }],
+ },
+ ],
+ });
+
+ await context.setStorageState({
+ cookies: [
+ {
+ domain: 'www.example.com',
+ name: 'foo',
+ value: 'bar',
+ path: '/',
+ expires: -1,
+ httpOnly: false,
+ secure: false,
+ sameSite: 'Lax',
+ },
+ ],
+ origins: [
+ {
+ origin: 'https://www.another.com',
+ localStorage: [{
+ name: 'name2',
+ value: 'value2',
+ }],
+ },
+ ],
+ });
+
+ expect(context.pages()).toHaveLength(1);
+ await expect(page).toHaveURL('https://www.example.com/');
+
+ await page.goto('https://www.another.com');
+ expect(await page.evaluate(() => document.cookie)).toBe('');
+ expect(await page.evaluate(() => window.localStorage['name1'])).toBe(undefined);
+ expect(await page.evaluate(() => window.localStorage['name2'])).toBe('value2');
+
+ await page.goto('https://www.example.com');
+ expect(await page.evaluate(() => document.cookie)).toBe('foo=bar');
+ expect(await page.evaluate(() => window.localStorage['name1'])).toBe(undefined);
+ expect(await page.evaluate(() => window.localStorage['name2'])).toBe(undefined);
+});