Skip to content

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

feat(storage): capture OPFS in storage state (#42248)

Yury Semikhatsky902a864ac629
diff --git a/docs/src/api/class-apirequestcontext.md b/docs/src/api/class-apirequestcontext.md
index 65ce2c1020..0adb320d9c 100644
--- a/docs/src/api/class-apirequestcontext.md
+++ b/docs/src/api/class-apirequestcontext.md
@@ -915,6 +915,12 @@ Returns storage state for this request context, contains current cookies and loc
Set to `true` to include IndexedDB in the storage state snapshot.
+### option: APIRequestContext.storageState.opfs
+* since: v1.63
+- `opfs` ?<boolean>
+
+Set to `true` to include the origin private file system in the storage state snapshot.
+
## property: APIRequestContext.tracing
* since: v1.60
- type: <[Tracing]>
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index 552cbe43d7..993a0d0e93 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -1566,7 +1566,7 @@ Whether to emulate network being offline for the browser context.
- `name` <[string]>
- `value` <[string]>
-Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB snapshot and virtual WebAuthn credentials.
+Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB snapshot, origin private file system snapshot and virtual WebAuthn credentials.
## async method: BrowserContext.storageState
* since: v1.8
@@ -1583,6 +1583,17 @@ 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.
+### option: BrowserContext.storageState.opfs
+* since: v1.63
+- `opfs` ?<boolean>
+
+Set to `true` to include the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system)
+in the storage state snapshot.
+
+:::note
+OPFS is currently not supported in ephemeral WebKit contexts.
+:::
+
### option: BrowserContext.storageState.credentials
* since: v1.61
- `credentials` ?<boolean>
@@ -1595,7 +1606,7 @@ Note that restoring the storage state that contains credentials will automatical
## async method: BrowserContext.setStorageState
* since: v1.59
-Clears the existing cookies, local storage, IndexedDB entries and virtual WebAuthn credentials, and sets the new storage
+Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual WebAuthn credentials, and sets the new storage
state. When the storage state contains credentials, the virtual WebAuthn authenticator is installed (equivalent to
[`method: Credentials.install`]), preventing all real authenticators from working in this context.
diff --git a/packages/injected/src/storageScript.ts b/packages/injected/src/storageScript.ts
index e373cd8a00..aae4653ce4 100644
--- a/packages/injected/src/storageScript.ts
+++ b/packages/injected/src/storageScript.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import { parseEvaluationResultValue, serializeAsCallArgument } from '@isomorphic/utilityScriptSerializers';
+import { parseEvaluationResultValue, serializeAsCallArgument, typedArrayToBase64 } from '@isomorphic/utilityScriptSerializers';
-import type { IndexedDBDatabase, OriginStorage, SetOriginStorage } from '@protocol/structs';
+import type { IndexedDBDatabase, OPFSEntry, OriginStorage, SetOriginStorage } from '@protocol/structs';
export type SerializedStorage = Omit<OriginStorage, 'origin'>;
@@ -24,8 +24,8 @@ export class StorageScript {
private _isFirefox: boolean;
private _global;
- constructor(isFirefox: boolean) {
- this._isFirefox = isFirefox;
+ constructor(browserName: string) {
+ this._isFirefox = browserName === 'firefox';
// eslint-disable-next-line no-restricted-globals
this._global = globalThis;
}
@@ -37,6 +37,20 @@ export class StorageScript {
});
}
+ private async _directoryEntries(directory: FileSystemDirectoryHandle): Promise<[string, FileSystemHandle][]> {
+ // Firefox Xray wrappers expose only string-named WebIDL members, so the async
+ // iterator has no Symbol.asyncIterator here ('directory.entries() is not
+ // iterable') and `for await` cannot be used. Drive the iterator manually.
+ const result: [string, FileSystemHandle][] = [];
+ const iterator = directory.entries();
+ while (true) {
+ const entry = await iterator.next();
+ if (entry.done)
+ return result;
+ result.push(entry.value);
+ }
+ }
+
private _isPlainObject(v: any) {
const ctor = v?.constructor;
if (this._isFirefox) {
@@ -137,17 +151,43 @@ export class StorageScript {
}
}
- async collect(recordIndexedDB: boolean): Promise<SerializedStorage> {
+ private async _collectOPFS(root: FileSystemDirectoryHandle): Promise<OPFSEntry[]> {
+ const collect = async (directory: FileSystemDirectoryHandle, parentPath: string): Promise<OPFSEntry[]> => {
+ const entries = await this._directoryEntries(directory);
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
+
+ const results = await Promise.all(entries.map(async ([name, handle]): Promise<OPFSEntry[]> => {
+ const path = parentPath ? `${parentPath}/${name}` : name;
+ if (handle.kind === 'directory')
+ return [{ path, type: 'directory' }, ...await collect(handle as FileSystemDirectoryHandle, path)];
+ const file = await (handle as FileSystemFileHandle).getFile();
+ const base64 = typedArrayToBase64(new Uint8Array(await file.arrayBuffer()));
+ return [{ path, type: 'file', base64 }];
+ }));
+ return results.flat();
+ };
+ return collect(root, '');
+ }
+
+ async collect(record: { indexedDB: boolean, opfs: boolean }): Promise<SerializedStorage> {
const localStorage = Object.keys(this._global.localStorage).map(name => ({ name, value: this._global.localStorage.getItem(name)! }));
- if (!recordIndexedDB)
- return { localStorage };
- try {
- const databases = await this._global.indexedDB.databases();
- const indexedDB = await Promise.all(databases.map(db => this._collectDB(db)));
- return { localStorage, indexedDB };
- } catch (e) {
- throw new Error('Unable to serialize IndexedDB: ' + e.message);
+ const result: SerializedStorage = { localStorage };
+ if (record.indexedDB) {
+ try {
+ const databases = await this._global.indexedDB.databases();
+ result.indexedDB = await Promise.all(databases.map(db => this._collectDB(db)));
+ } catch (e) {
+ throw new Error('Unable to serialize IndexedDB: ' + e.message);
+ }
+ }
+ if (record.opfs) {
+ try {
+ result.opfs = await this._collectOPFS(await this._global.navigator.storage.getDirectory());
+ } catch (e) {
+ throw new Error('Unable to serialize OPFS: ' + e.message);
+ }
}
+ return result;
}
private async _restoreDB(dbInfo: IndexedDBDatabase) {
@@ -183,6 +223,53 @@ export class StorageScript {
}
}
+ private async _restoreOPFS(originState: SetOriginStorage | undefined) {
+ let root: FileSystemDirectoryHandle;
+ try {
+ root = await this._global.navigator.storage.getDirectory();
+ } catch (e) {
+ // OPFS may be unavailable, e.g. on insecure origins or in WebKit contexts
+ // that fail with 'unknown transient reason'. There is nothing to clear then,
+ // so only fail when there are entries to restore.
+ if (originState?.opfs === undefined)
+ return;
+ throw e;
+ }
+
+ await Promise.all((await this._directoryEntries(root)).map(([name]) => root.removeEntry(name, { recursive: true })));
+
+ const entries = originState?.opfs ?? [];
+ if (!entries.length)
+ return;
+
+ for (const entry of entries) {
+ const parts = entry.path.split('/');
+ let directory = root;
+ for (const part of parts.slice(0, -1))
+ directory = await directory.getDirectoryHandle(part, { create: true });
+
+ const name = parts[parts.length - 1];
+ if (entry.type === 'directory') {
+ await directory.getDirectoryHandle(name, { create: true });
+ continue;
+ }
+ const blob = await this._blobFromBase64(entry.base64!);
+ const handle = await directory.getFileHandle(name, { create: true });
+ const writable = await handle.createWritable();
+ await writable.write(blob);
+ await writable.close();
+ }
+ }
+
+ // Decode through the page's own fetch so that the resulting blob belongs to the page.
+ // The Firefox utility world is a sandbox with an extended principal, so the page is
+ // denied access to objects allocated here and writing a Uint8Array built in this world
+ // fails with 'Permission denied to access property "data"'.
+ private async _blobFromBase64(base64: string): Promise<Blob> {
+ const response = await this._global.fetch(`data:application/octet-stream;base64,${base64}`);
+ return response.blob();
+ }
+
async restore(originState: SetOriginStorage | undefined) {
// Clean Service Workers.
const registrations = this._global.navigator.serviceWorker ? await this._global.navigator.serviceWorker.getRegistrations() : [];
@@ -213,5 +300,11 @@ export class StorageScript {
this._global.localStorage.clear();
for (const { name, value } of (originState?.localStorage || []))
this._global.localStorage.setItem(name, value);
+
+ try {
+ await this._restoreOPFS(originState);
+ } catch (e) {
+ throw new Error('Unable to restore OPFS: ' + e.message);
+ }
}
}
diff --git a/packages/isomorphic/utilityScriptSerializers.ts b/packages/isomorphic/utilityScriptSerializers.ts
index a6556e2dc4..7e5264e303 100644
--- a/packages/isomorphic/utilityScriptSerializers.ts
+++ b/packages/isomorphic/utilityScriptSerializers.ts
@@ -110,7 +110,7 @@ const typedArrayConstructors: Record<TypedArrayKind, Function> = {
bui64: BigUint64Array,
};
-function typedArrayToBase64(array: any) {
+export function typedArrayToBase64(array: any) {
/**
* Firefox does not support iterating over typed arrays, so we use `.toBase64`.
* Error: 'Accessing TypedArray data over Xrays is slow, and forbidden in order to encourage performant code. To copy TypedArrays across origin boundaries, consider using Components.utils.cloneInto().'
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 74cb7ada8b..2acee94c52 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -10605,10 +10605,11 @@ export interface BrowserContext {
setOffline(offline: boolean): Promise<void>;
/**
- * Clears the existing cookies, local storage, IndexedDB entries and virtual WebAuthn credentials, and sets the new
- * storage state. When the storage state contains credentials, the virtual WebAuthn authenticator is installed
- * (equivalent to [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install)),
- * preventing all real authenticators from working in this context.
+ * Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual
+ * WebAuthn credentials, and sets the new storage state. When the storage state contains credentials, the virtual
+ * WebAuthn authenticator is installed (equivalent to
+ * [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install)), preventing all
+ * real authenticators from working in this context.
*
* **Usage**
*
@@ -10674,7 +10675,7 @@ export interface BrowserContext {
/**
* Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB
- * snapshot and virtual WebAuthn credentials.
+ * snapshot, origin private file system snapshot and virtual WebAuthn credentials.
* @param options
*/
storageState(options?: {
@@ -10698,6 +10699,16 @@ export interface BrowserContext {
*/
indexedDB?: boolean;
+ /**
+ * Set to `true` to include the
+ * [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system)
+ * in the storage state snapshot.
+ *
+ * **NOTE** OPFS is currently not supported in ephemeral WebKit contexts.
+ *
+ */
+ opfs?: boolean;
+
/**
* The file path to save the storage state to. If
* [`path`](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state-option-path) is a
@@ -20318,6 +20329,11 @@ export interface APIRequestContext {
*/
indexedDB?: boolean;
+ /**
+ * Set to `true` to include the origin private file system in the storage state snapshot.
+ */
+ opfs?: boolean;
+
/**
* The file path to save the storage state to. If
* [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts
index c1e22cdf12..3d3614a00d 100644
--- a/packages/playwright-core/src/client/browserContext.ts
+++ b/packages/playwright-core/src/client/browserContext.ts
@@ -479,8 +479,8 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
});
}
- async storageState(options: { path?: string, indexedDB?: boolean, credentials?: boolean } = {}): Promise<StorageState> {
- const state = await this._channel.storageState({ indexedDB: options.indexedDB, credentials: options.credentials }, kNoTimeout);
+ async storageState(options: { path?: string, indexedDB?: boolean, opfs?: boolean, credentials?: boolean } = {}): Promise<StorageState> {
+ const state = await this._channel.storageState({ indexedDB: options.indexedDB, opfs: options.opfs, credentials: options.credentials }, kNoTimeout);
if (options.path) {
await mkdirIfNeeded(options.path);
await fs.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');
diff --git a/packages/playwright-core/src/client/channels.d.ts b/packages/playwright-core/src/client/channels.d.ts
index 84080820cc..aecf4c95c1 100644
--- a/packages/playwright-core/src/client/channels.d.ts
+++ b/packages/playwright-core/src/client/channels.d.ts
@@ -15,8 +15,8 @@
*/
// This file is generated by generate_channels.js, do not edit manually.
-import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
-export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
export type TimeoutOptions = { signal: AbortSignal | undefined, timeout: number };
@@ -631,9 +631,11 @@ export type APIRequestContextFetchLogResult = {
};
export type APIRequestContextStorageStateParams = {
indexedDB?: boolean,
+ opfs?: boolean,
};
export type APIRequestContextStorageStateOptions = {
indexedDB?: boolean,
+ opfs?: boolean,
};
export type APIRequestContextStorageStateResult = {
cookies: NetworkCookie[],
@@ -1489,10 +1491,12 @@ export type BrowserContextSetOfflineOptions = {
export type BrowserContextSetOfflineResult = void;
export type BrowserContextStorageStateParams = {
indexedDB?: boolean,
+ opfs?: boolean,
credentials?: boolean,
};
export type BrowserContextStorageStateOptions = {
indexedDB?: boolean,
+ opfs?: boolean,
credentials?: boolean,
};
export type BrowserContextStorageStateResult = {
diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.ts
index cba0845ca3..415568750e 100644
--- a/packages/playwright-core/src/client/fetch.ts
+++ b/packages/playwright-core/src/client/fetch.ts
@@ -269,8 +269,8 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextCh
});
}
- async storageState(options: { path?: string, indexedDB?: boolean } = {}): Promise<StorageState> {
- const state = await this._channel.storageState({ indexedDB: options.indexedDB }, kNoTimeout);
+ async storageState(options: { path?: string, indexedDB?: boolean, opfs?: boolean } = {}): Promise<StorageState> {
+ const state = await this._channel.storageState({ indexedDB: options.indexedDB, opfs: options.opfs }, kNoTimeout);
if (options.path) {
await mkdirIfNeeded(options.path);
await fs.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts
index c1a2a58378..33b5331e64 100644
--- a/packages/playwright-core/src/server/browserContext.ts
+++ b/packages/playwright-core/src/server/browserContext.ts
@@ -616,7 +616,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
this._origins.add(origin);
}
- async storageState(progress: Progress, indexedDB = false, credentials = false): Promise<channels.BrowserContextStorageStateResult> {
+ async storageState(progress: Progress, { indexedDB = false, opfs = false, credentials = false }: { indexedDB?: boolean, opfs?: boolean, credentials?: boolean } = {}): Promise<channels.BrowserContextStorageStateResult> {
const result: channels.BrowserContextStorageStateResult = {
cookies: await this.cookies(progress),
origins: []
@@ -624,12 +624,13 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
if (credentials)
result.credentials = await progress.race(this.credentials.get());
const originsToSave = new Set(this._origins);
+ const hasStorage = (storage: SerializedStorage) => !!(storage.localStorage.length || storage.indexedDB?.length || storage.opfs?.length);
const collectScript = `(() => {
const module = {};
${rawStorageSource.source}
- const script = new (module.exports.StorageScript())(${this._browser.options.name === 'firefox'});
- return script.collect(${indexedDB});
+ const script = new (module.exports.StorageScript())(${JSON.stringify(this._browser.options.name)});
+ return script.collect({ indexedDB: ${indexedDB}, opfs: ${opfs} });
})()`;
// First try collecting storage stage from existing pages.
@@ -639,8 +640,8 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
continue;
try {
const storage: SerializedStorage = await progress.race(page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, 'utility'));
- if (storage.localStorage.length || storage.indexedDB?.length)
- result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
+ if (hasStorage(storage))
+ result.origins.push({ origin, ...storage });
originsToSave.delete(origin);
} catch {
// When failed on the live page, we'll retry on the blank page below.
@@ -658,8 +659,8 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
const frame = page.mainFrame();
await frame.gotoImpl(progress, origin, {});
const storage: SerializedStorage = await frame.evaluateExpression(progress, collectScript, { world: 'utility' });
- if (storage.localStorage.length || storage.indexedDB?.length)
- result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
+ if (hasStorage(storage))
+ result.origins.push({ origin, ...storage });
}
} finally {
await page.close(progress);
@@ -713,7 +714,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
const restoreScript = `(() => {
const module = {};
${rawStorageSource.source}
- const script = new (module.exports.StorageScript())(${this._browser.options.name === 'firefox'});
+ const script = new (module.exports.StorageScript())(${JSON.stringify(this._browser.options.name)});
return script.restore(${JSON.stringify(newOrigins.get(origin))});
})()`;
await frame.evaluateExpression(progress, restoreScript, { world: 'utility' });
diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.ts
index 8e4d1a42dd..1119ef3267 100644
--- a/packages/playwright-core/src/server/channels.d.ts
+++ b/packages/playwright-core/src/server/channels.d.ts
@@ -18,8 +18,8 @@
import type { Progress } from './progress';
-import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
-export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
// ----------- Initializer Traits -----------
export type InitializerTraits<T> =
@@ -632,9 +632,11 @@ export type APIRequestContextFetchLogResult = {
};
export type APIRequestContextStorageStateParams = {
indexedDB?: boolean,
+ opfs?: boolean,
};
export type APIRequestContextStorageStateOptions = {
indexedDB?: boolean,
+ opfs?: boolean,
};
export type APIRequestContextStorageStateResult = {
cookies: NetworkCookie[],
@@ -1490,10 +1492,12 @@ export type BrowserContextSetOfflineOptions = {
export type BrowserContextSetOfflineResult = void;
export type BrowserContextStorageStateParams = {
indexedDB?: boolean,
+ opfs?: boolean,
credentials?: boolean,
};
export type BrowserContextStorageStateOptions = {
indexedDB?: boolean,
+ opfs?: boolean,
credentials?: boolean,
};
export type BrowserContextStorageStateResult = {
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index ed8745d049..3858519d82 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -343,7 +343,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
}
async storageState(params: channels.BrowserContextStorageStateParams, progress: Progress): Promise<channels.BrowserContextStorageStateResult> {
- return await this._context.storageState(progress, params.indexedDB, params.credentials);
+ return await this._context.storageState(progress, params);
}
async setStorageState(params: channels.BrowserContextSetStorageStateParams, progress: Progress): Promise<void> {
diff --git a/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts b/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts
index 8a7cfd3e84..8e4f5b8bb0 100644
--- a/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts
+++ b/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts
@@ -212,7 +212,7 @@ export class APIRequestContextDispatcher extends Dispatcher<APIRequestContext, c
}
async storageState(params: channels.APIRequestContextStorageStateParams, progress: Progress): Promise<channels.APIRequestContextStorageStateResult> {
- return await this._object.storageState(progress, params.indexedDB);
+ return await this._object.storageState(progress, params);
}
async dispose(params: channels.APIRequestContextDisposeParams, progress: Progress): Promise<void> {
diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.ts
index 012c71d473..b154ce6307 100644
--- a/packages/playwright-core/src/server/fetch.ts
+++ b/packages/playwright-core/src/server/fetch.ts
@@ -134,7 +134,7 @@ export abstract class APIRequestContext extends SdkObject {
APIRequestContext.allInstances.add(this);
}
- abstract storageState(progress: Progress, indexedDB?: boolean): Promise<channels.APIRequestContextStorageStateResult>;
+ abstract storageState(progress: Progress, params: { indexedDB?: boolean, opfs?: boolean }): Promise<channels.APIRequestContextStorageStateResult>;
fetchResponseBody(progress: Progress, fetchUid: string): Buffer | undefined {
return this.fetchResponses.get(fetchUid);
@@ -747,8 +747,8 @@ export class BrowserContextAPIRequestContext extends APIRequestContext {
return await this._context.cookies(progress, url.toString());
}
- override async storageState(progress: Progress, indexedDB?: boolean): Promise<channels.APIRequestContextStorageStateResult> {
- return this._context.storageState(progress, indexedDB);
+ override async storageState(progress: Progress, params: { indexedDB?: boolean, opfs?: boolean }): Promise<channels.APIRequestContextStorageStateResult> {
+ return this._context.storageState(progress, params);
}
}
@@ -762,7 +762,7 @@ export class GlobalAPIRequestContext extends APIRequestContext {
constructor(playwright: Playwright, options: channels.PlaywrightNewRequestOptions) {
super(playwright);
if (options.storageState) {
- this._origins = options.storageState.origins?.map(origin => ({ indexedDB: [], ...origin }));
+ this._origins = options.storageState.origins?.map(origin => ({ indexedDB: [], opfs: [], ...origin }));
this._cookieStore.addCookies(options.storageState.cookies || []);
}
verifyClientCertificates(options.clientCertificates);
@@ -803,10 +803,14 @@ export class GlobalAPIRequestContext extends APIRequestContext {
return this._cookieStore.cookies(url);
}
- override async storageState(progress: Progress, indexedDB = false): Promise<channels.APIRequestContextStorageStateResult> {
+ override async storageState(progress: Progress, { indexedDB = false, opfs = false }: { indexedDB?: boolean, opfs?: boolean }): Promise<channels.APIRequestContextStorageStateResult> {
return {
cookies: this._cookieStore.allCookies(),
- origins: (this._origins || []).map(origin => ({ ...origin, indexedDB: indexedDB ? origin.indexedDB : [] })),
+ origins: (this._origins || []).map(origin => ({
+ ...origin,
+ indexedDB: indexedDB ? origin.indexedDB : [],
+ opfs: opfs ? origin.opfs : undefined,
+ })),
};
}
}
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 74cb7ada8b..2acee94c52 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -10605,10 +10605,11 @@ export interface BrowserContext {
setOffline(offline: boolean): Promise<void>;
/**
- * Clears the existing cookies, local storage, IndexedDB entries and virtual WebAuthn credentials, and sets the new
- * storage state. When the storage state contains credentials, the virtual WebAuthn authenticator is installed
- * (equivalent to [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install)),
- * preventing all real authenticators from working in this context.
+ * Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual
+ * WebAuthn credentials, and sets the new storage state. When the storage state contains credentials, the virtual
+ * WebAuthn authenticator is installed (equivalent to
+ * [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install)), preventing all
+ * real authenticators from working in this context.
*
* **Usage**
*
@@ -10674,7 +10675,7 @@ export interface BrowserContext {
/**
* Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB
- * snapshot and virtual WebAuthn credentials.
+ * snapshot, origin private file system snapshot and virtual WebAuthn credentials.
* @param options
*/
storageState(options?: {
@@ -10698,6 +10699,16 @@ export interface BrowserContext {
*/
indexedDB?: boolean;
+ /**
+ * Set to `true` to include the
+ * [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system)
+ * in the storage state snapshot.
+ *
+ * **NOTE** OPFS is currently not supported in ephemeral WebKit contexts.
+ *
+ */
+ opfs?: boolean;
+
/**
* The file path to save the storage state to. If
* [`path`](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state-option-path) is a
@@ -20318,6 +20329,11 @@ export interface APIRequestContext {
*/
indexedDB?: boolean;
+ /**
+ * Set to `true` to include the origin private file system in the storage state snapshot.
+ */
+ opfs?: boolean;
+
/**
* The file path to save the storage state to. If
* [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is
diff --git a/packages/protocol/spec/api.yml b/packages/protocol/spec/api.yml
index 96988d00a5..f8ef4aae2c 100644
--- a/packages/protocol/spec/api.yml
+++ b/packages/protocol/spec/api.yml
@@ -73,6 +73,7 @@ APIRequestContext:
group: configuration
parameters:
indexedDB: boolean?
+ opfs: boolean?
returns:
cookies:
type: array
diff --git a/packages/protocol/spec/browserContext.yml b/packages/protocol/spec/browserContext.yml
index ecdba7664b..738cb6a3f8 100644
--- a/packages/protocol/spec/browserContext.yml
+++ b/packages/protocol/spec/browserContext.yml
@@ -179,6 +179,7 @@ BrowserContext:
group: configuration
parameters:
indexedDB: boolean?
+ opfs: boolean?
credentials: boolean?
returns:
cookies:
diff --git a/packages/protocol/spec/playwright.yml b/packages/protocol/spec/playwright.yml
index 401a9cf153..b4c9651b2e 100644
--- a/packages/protocol/spec/playwright.yml
+++ b/packages/protocol/spec/playwright.yml
@@ -329,6 +329,17 @@ IndexedDBDatabase:
multiEntry: boolean
unique: boolean
+OPFSEntry:
+ type: object
+ properties:
+ path: string
+ type:
+ type: enum
+ literals:
+ - file
+ - directory
+ base64: string?
+
SetOriginStorage:
type: object
properties:
@@ -339,6 +350,9 @@ SetOriginStorage:
indexedDB:
type: array?
items: IndexedDBDatabase
+ opfs:
+ type: array?
+ items: OPFSEntry
OriginStorage:
type: object
@@ -350,6 +364,9 @@ OriginStorage:
indexedDB:
type: array?
items: IndexedDBDatabase
+ opfs:
+ type: array?
+ items: OPFSEntry
RecordHarOptions:
type: object
diff --git a/packages/protocol/src/structs.d.ts b/packages/protocol/src/structs.d.ts
index 9ee0c14461..9c637e7398 100644
--- a/packages/protocol/src/structs.d.ts
+++ b/packages/protocol/src/structs.d.ts
@@ -242,16 +242,24 @@ export type IndexedDBDatabase = {
}[],
};
+export type OPFSEntry = {
+ path: string,
+ type: 'file' | 'directory',
+ base64?: string,
+};
+
export type SetOriginStorage = {
origin: string,
localStorage: NameValue[],
indexedDB?: IndexedDBDatabase[],
+ opfs?: OPFSEntry[],
};
export type OriginStorage = {
origin: string,
localStorage: NameValue[],
indexedDB?: IndexedDBDatabase[],
+ opfs?: OPFSEntry[],
};
export type RecordHarOptions = {
diff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.ts
index 46baf155da..565a6a18cf 100644
--- a/packages/protocol/src/validator.ts
+++ b/packages/protocol/src/validator.ts
@@ -324,6 +324,7 @@ scheme.APIRequestContextFetchLogResult = tObject({
});
scheme.APIRequestContextStorageStateParams = tObject({
indexedDB: tOptional(tBoolean),
+ opfs: tOptional(tBoolean),
});
scheme.APIRequestContextStorageStateResult = tObject({
cookies: tArray(tType('NetworkCookie')),
@@ -818,6 +819,7 @@ scheme.BrowserContextSetOfflineParams = tObject({
scheme.BrowserContextSetOfflineResult = tOptional(tObject({}));
scheme.BrowserContextStorageStateParams = tObject({
indexedDB: tOptional(tBoolean),
+ opfs: tOptional(tBoolean),
credentials: tOptional(tBoolean),
});
scheme.BrowserContextStorageStateResult = tObject({
@@ -2847,15 +2849,22 @@ scheme.IndexedDBDatabase = tObject({
})),
})),
});
+scheme.OPFSEntry = tObject({
+ path: tString,
+ type: tEnum(['file', 'directory']),
+ base64: tOptional(tString),
+});
scheme.SetOriginStorage = tObject({
origin: tString,
localStorage: tArray(tType('NameValue')),
indexedDB: tOptional(tArray(tType('IndexedDBDatabase'))),
+ opfs: tOptional(tArray(tType('OPFSEntry'))),
});
scheme.OriginStorage = tObject({
origin: tString,
localStorage: tArray(tType('NameValue')),
indexedDB: tOptional(tArray(tType('IndexedDBDatabase'))),
+ opfs: tOptional(tArray(tType('OPFSEntry'))),
});
scheme.RecordHarOptions = tObject({
content: tOptional(tEnum(['embed', 'attach', 'omit'])),
diff --git a/tests/library/browsercontext-storage-state.spec.ts b/tests/library/browsercontext-storage-state.spec.ts
index b25995217f..3a42e2ed78 100644
--- a/tests/library/browsercontext-storage-state.spec.ts
+++ b/tests/library/browsercontext-storage-state.spec.ts
@@ -200,6 +200,118 @@ it('should round-trip through the file', async ({ contextFactory, channel }, tes
await context3.close();
});
+it('should round-trip OPFS', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41400' } }, async ({ browserName, contextFactory, page, server }, testInfo) => {
+ it.skip(browserName === 'webkit', 'OPFS is unavailable in non-persistent WebKit contexts');
+
+ await page.goto(server.EMPTY_PAGE);
+ await page.evaluate(async () => {
+ const root = await navigator.storage.getDirectory();
+ const nested = await root.getDirectoryHandle('nested', { create: true });
+ await nested.getDirectoryHandle('empty', { create: true });
+
+ const binary = await nested.getFileHandle('data.bin', { create: true });
+ const binaryWritable = await binary.createWritable();
+ await binaryWritable.write(new Uint8Array([0, 1, 2, 255]));
+ await binaryWritable.close();
+
+ const text = await root.getFileHandle('hello.txt', { create: true });
+ const textWritable = await text.createWritable();
+ await textWritable.write('Hello, world!');
+ await textWritable.close();
+ });
+
+ expect(await page.context().storageState()).toEqual({ cookies: [], origins: [] });
+
+ const path = testInfo.outputPath('storage-state.json');
+ const storageState = await page.context().storageState({ path, opfs: true });
+ expect(storageState.origins).toEqual([{
+ origin: server.PREFIX,
+ localStorage: [],
+ opfs: [
+ { path: 'hello.txt', type: 'file', base64: 'SGVsbG8sIHdvcmxkIQ==' },
+ { path: 'nested', type: 'directory' },
+ { path: 'nested/data.bin', type: 'file', base64: 'AAEC/w==' },
+ { path: 'nested/empty', type: 'directory' },
+ ],
+ }]);
+ expect(JSON.parse(await fs.promises.readFile(path, 'utf8'))).toEqual(storageState);
+ expect(await page.context().request.storageState({ opfs: true })).toEqual(storageState);
+
+ const checkContext = async (context: BrowserContext) => {
+ expect(await context.storageState({ opfs: true })).toEqual(storageState);
+ const checkPage = await context.newPage();
+ await checkPage.goto(server.EMPTY_PAGE);
+ expect(await checkPage.evaluate(async () => {
+ const root = await navigator.storage.getDirectory();
+ const hello = await (await root.getFileHandle('hello.txt')).getFile();
+ const nested = await root.getDirectoryHandle('nested');
+ const data = await (await nested.getFileHandle('data.bin')).getFile();
+ const empty = await nested.getDirectoryHandle('empty');
+ const emptyEntries = [];
+ for await (const name of empty.keys())
+ emptyEntries.push(name);
+ return {
+ text: await hello.text(),
+ bytes: [...new Uint8Array(await data.arrayBuffer())],
+ empty: emptyEntries,
+ };
+ })).toEqual({
+ text: 'Hello, world!',
+ bytes: [0, 1, 2, 255],
+ empty: [],
+ });
+ };
+
+ const context2 = await contextFactory({ storageState: path });
+ await checkContext(context2);
+ await context2.close();
+
+ const context3 = await contextFactory();
+ const page3 = await context3.newPage();
+ await page3.goto(server.EMPTY_PAGE);
+ await page3.evaluate(async () => {
+ const root = await navigator.storage.getDirectory();
+ await root.getFileHandle('stale.txt', { create: true });
+ });
+ await context3.setStorageState(storageState);
+ await checkContext(context3);
+ await context3.close();
+});
+
+it('should round-trip OPFS in a persistent WebKit context', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41400' } }, async ({ browserName, launchPersistent, server }) => {
+ it.skip(browserName !== 'webkit');
+
+ const { context, page } = await launchPersistent();
+ await page.goto(server.EMPTY_PAGE);
+ await page.evaluate(async () => {
+ const root = await navigator.storage.getDirectory();
+ await root.getDirectoryHandle('empty', { create: true });
+ const file = await root.getFileHandle('hello.txt', { create: true });
+ const writable = await file.createWritable();
+ await writable.write('Hello, world!');
+ await writable.close();
+ });
+
+ const storageState = await context.storageState({ opfs: true });
+ expect(storageState.origins).toEqual([{
+ origin: server.PREFIX,
+ localStorage: [],
+ opfs: [
+ { path: 'empty', type: 'directory' },
+ { path: 'hello.txt', type: 'file', base64: 'SGVsbG8sIHdvcmxkIQ==' },
+ ],
+ }]);
+
+ await page.evaluate(async () => {
+ const root = await navigator.storage.getDirectory();
+ await root.removeEntry('empty', { recursive: true });
+ await root.removeEntry('hello.txt');
+ await root.getFileHandle('stale.txt', { create: true });
+ });
+ await context.setStorageState(storageState);
+ expect(await context.storageState({ opfs: true })).toEqual(storageState);
+});
+
it('should capture cookies', async ({ server, context, page, contextFactory }) => {
server.setRoute('/setcookie.html', (req, res) => {
res.setHeader('Set-Cookie', ['a=b', 'empty=']);
diff --git a/tests/library/global-fetch-cookie.spec.ts b/tests/library/global-fetch-cookie.spec.ts
index f747a5cd3b..32d8b58dfc 100644
--- a/tests/library/global-fetch-cookie.spec.ts
+++ b/tests/library/global-fetch-cookie.spec.ts
@@ -345,7 +345,7 @@ it('should export cookies to storage state', async ({ request, server }) => {
});
});
-it('should preserve local storage on import/export of storage state', async ({ playwright, server }) => {
+it('should preserve origin storage on import/export of storage state', async ({ playwright, server }) => {
const storageState: StorageStateType = {
cookies: [
{
@@ -367,6 +367,17 @@ it('should preserve local storage on import/export of storage state', async ({ p
value: 'value1'
}],
...{
+ opfs: [
+ {
+ path: 'hello.txt',
+ type: 'file',
+ base64: 'SGVsbG8sIHdvcmxkIQ==',
+ },
+ {
+ path: 'empty',
+ type: 'directory',
+ },
+ ],
indexedDB: [
{
name: 'db',
@@ -392,7 +403,7 @@ it('should preserve local storage on import/export of storage state', async ({ p
};
const request = await playwright.request.newContext({ storageState });
await request.get(server.EMPTY_PAGE);
- const exportedState = await request.storageState({ indexedDB: true });
+ const exportedState = await request.storageState({ indexedDB: true, opfs: true });
expect(exportedState).toEqual(storageState);
await request.dispose();
});