Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/src/api/class-browsercontext.md
Original file line number Diff line number Diff line change
Expand Up @@ -1500,6 +1500,46 @@ Returns storage state for this browser context, contains current cookies, local
Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage state snapshot.
If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this.

## async method: BrowserContext.setStorageState
* since: v1.59

Clears the existing cookies, local storage and IndexedDB entries for all origins and sets the new storage state.

**Usage**

```js
// Load storage state from a file and apply it to the context.
await context.setStorageState('state.json');
```

```java
// Load storage state from a file and apply it to the context.
context.setStorageState(Paths.get("state.json"));
```

```python async
# Load storage state from a file and apply it to the context.
await context.set_storage_state("state.json")
```

```python sync
# Load storage state from a file and apply it to the context.
context.set_storage_state("state.json")
```

```csharp
// Load storage state from a file and apply it to the context.
await context.SetStorageStateAsync("state.json");
```

### param: BrowserContext.setStorageState.storageState = %%-js-python-context-option-storage-state-%%
* since: v1.59
* langs: js, python

### param: BrowserContext.setStorageState.storageState = %%-csharp-java-context-option-storage-state-path-%%
* since: v1.59
* langs: csharp, java

## property: BrowserContext.tracing
* since: v1.12
- type: <[Tracing]>
Expand Down
65 changes: 65 additions & 0 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9611,6 +9611,71 @@ export interface BrowserContext {
*/
setOffline(offline: boolean): Promise<void>;

/**
* Clears the existing cookies, local storage and IndexedDB entries for all origins and sets the new storage state.
*
* **Usage**
*
* ```js
* // Load storage state from a file and apply it to the context.
* await context.setStorageState('state.json');
* ```
*
* @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.
Expand Down
5 changes: 5 additions & 0 deletions packages/playwright-core/src/client/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,11 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
return state;
}

async setStorageState(storageState: string | SetStorageState): Promise<void> {
const state = await prepareStorageState(this._platform, storageState);
await this._channel.setStorageState({ storageState: state });
}

backgroundPages(): Page[] {
return [];
}
Expand Down
7 changes: 7 additions & 0 deletions packages/playwright-core/src/protocol/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,13 @@ scheme.BrowserContextStorageStateResult = tObject({
cookies: tArray(tType('NetworkCookie')),
origins: tArray(tType('OriginStorage')),
});
scheme.BrowserContextSetStorageStateParams = tObject({
storageState: tOptional(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({
Expand Down
2 changes: 1 addition & 1 deletion packages/playwright-core/src/server/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
return this._creatingStorageStatePage;
}

async setStorageState(progress: Progress, state: channels.BrowserNewContextParams['storageState'], mode: 'initial' | 'resetForReuse') {
async setStorageState(progress: Progress, state: channels.BrowserNewContextParams['storageState'], mode: 'initial' | 'resetForReuse' | 'api') {
let page: Page | undefined;
let interceptor: network.RouteHandler | undefined;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,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<void> {
await this._context.setStorageState(progress, params.storageState, 'api');
}

async close(params: channels.BrowserContextCloseParams, progress: Progress): Promise<void> {
progress.metadata.potentiallyClosesScope = true;
await this._context.close(params);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const methodMetainfo = new Map<string, { internal?: boolean, title?: stri
['APIRequestContext.fetch', { title: '{method} "{url}"', }],
['APIRequestContext.fetchResponseBody', { title: 'Get response body', group: 'getter', }],
['APIRequestContext.fetchLog', { internal: true, }],
['APIRequestContext.storageState', { title: 'Get storage state', }],
['APIRequestContext.storageState', { title: 'Get storage state', group: 'configuration', }],
['APIRequestContext.disposeAPIResponse', { internal: true, }],
['APIRequestContext.dispose', { internal: true, }],
['LocalUtils.zip', { internal: true, }],
Expand Down Expand Up @@ -84,7 +84,8 @@ export const methodMetainfo = new Map<string, { internal?: boolean, title?: stri
['BrowserContext.setNetworkInterceptionPatterns', { title: 'Route requests', group: 'route', }],
['BrowserContext.setWebSocketInterceptionPatterns', { title: 'Route WebSockets', group: 'route', }],
['BrowserContext.setOffline', { title: 'Set offline mode', }],
['BrowserContext.storageState', { title: 'Get storage state', }],
['BrowserContext.storageState', { title: 'Get storage state', group: 'configuration', }],
['BrowserContext.setStorageState', { title: 'Set storage state', group: 'configuration', }],
['BrowserContext.pause', { title: 'Pause', }],
['BrowserContext.enableRecorder', { internal: true, }],
['BrowserContext.disableRecorder', { internal: true, }],
Expand Down
65 changes: 65 additions & 0 deletions packages/playwright-core/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9611,6 +9611,71 @@ export interface BrowserContext {
*/
setOffline(offline: boolean): Promise<void>;

/**
* Clears the existing cookies, local storage and IndexedDB entries for all origins and sets the new storage state.
*
* **Usage**
*
* ```js
* // Load storage state from a file and apply it to the context.
* await context.setStorageState('state.json');
* ```
*
* @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.
Expand Down
14 changes: 14 additions & 0 deletions packages/protocol/src/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1597,6 +1597,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>;
Expand Down Expand Up @@ -1845,6 +1846,19 @@ export type BrowserContextStorageStateResult = {
cookies: NetworkCookie[],
origins: OriginStorage[],
};
export type BrowserContextSetStorageStateParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
},
};
export type BrowserContextSetStorageStateOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
},
};
export type BrowserContextSetStorageStateResult = void;
export type BrowserContextPauseParams = {};
export type BrowserContextPauseOptions = {};
export type BrowserContextPauseResult = void;
Expand Down
16 changes: 16 additions & 0 deletions packages/protocol/src/protocol.yml
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ APIRequestContext:

storageState:
title: Get storage state
group: configuration
parameters:
indexedDB: boolean?
returns:
Expand Down Expand Up @@ -1299,6 +1300,7 @@ BrowserContext:

storageState:
title: Get storage state
group: configuration
parameters:
indexedDB: boolean?
returns:
Expand All @@ -1309,6 +1311,20 @@ BrowserContext:
type: array
items: OriginStorage

setStorageState:
title: Set storage state
group: configuration
parameters:
storageState:
type: object?
properties:
cookies:
type: array?
items: SetNetworkCookie
origins:
type: array?
items: SetOriginStorage

pause:
title: Pause

Expand Down
Loading
Loading