Skip to content

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

feat(api): add APIRequestContext.cookies and clearCookies (#43052)

Yury Semikhatskyb630e71fcda7
diff --git a/docs/src/api/class-apirequestcontext.md b/docs/src/api/class-apirequestcontext.md
index a977960c04..e467b30873 100644
--- a/docs/src/api/class-apirequestcontext.md
+++ b/docs/src/api/class-apirequestcontext.md
@@ -155,6 +155,88 @@ await request.AddCookiesAsync(new[] { cookie1, cookie2 });
### param: APIRequestContext.addCookies.cookies = %%-add-cookies-param-%%
* since: v1.64
+## async method: APIRequestContext.clearCookies
+* since: v1.64
+
+Removes cookies from this request context. Accepts optional filter. For [`property: BrowserContext.request`]
+and [`property: Page.request`], this is equivalent to calling [`method: BrowserContext.clearCookies`] on the corresponding browser context.
+
+**Usage**
+
+```js
+await request.clearCookies();
+await request.clearCookies({ name: 'session-id' });
+await request.clearCookies({ domain: 'my-origin.com' });
+await request.clearCookies({ domain: /.*my-origin\.com/ });
+await request.clearCookies({ path: '/api/v1' });
+await request.clearCookies({ name: 'session-id', domain: 'my-origin.com' });
+```
+
+```java
+request.clearCookies();
+request.clearCookies(new APIRequestContext.ClearCookiesOptions().setName("session-id"));
+request.clearCookies(new APIRequestContext.ClearCookiesOptions().setDomain("my-origin.com"));
+request.clearCookies(new APIRequestContext.ClearCookiesOptions().setPath("/api/v1"));
+request.clearCookies(new APIRequestContext.ClearCookiesOptions()
+ .setName("session-id")
+ .setDomain("my-origin.com"));
+```
+
+```python async
+await request.clear_cookies()
+await request.clear_cookies(name="session-id")
+await request.clear_cookies(domain="my-origin.com")
+await request.clear_cookies(path="/api/v1")
+await request.clear_cookies(name="session-id", domain="my-origin.com")
+```
+
+```python sync
+request.clear_cookies()
+request.clear_cookies(name="session-id")
+request.clear_cookies(domain="my-origin.com")
+request.clear_cookies(path="/api/v1")
+request.clear_cookies(name="session-id", domain="my-origin.com")
+```
+
+```csharp
+await request.ClearCookiesAsync();
+await request.ClearCookiesAsync(new() { Name = "session-id" });
+await request.ClearCookiesAsync(new() { Domain = "my-origin.com" });
+await request.ClearCookiesAsync(new() { Path = "/api/v1" });
+await request.ClearCookiesAsync(new() { Name = "session-id", Domain = "my-origin.com" });
+```
+
+### option: APIRequestContext.clearCookies.name = %%-clear-cookies-option-name-%%
+* since: v1.64
+
+### option: APIRequestContext.clearCookies.domain = %%-clear-cookies-option-domain-%%
+* since: v1.64
+
+### option: APIRequestContext.clearCookies.path = %%-clear-cookies-option-path-%%
+* since: v1.64
+
+## async method: APIRequestContext.cookies
+* since: v1.64
+- returns: <[Array]<[Object]>>
+ * alias: Cookie
+ * alias-csharp: BrowserContextCookiesResult
+ - `name` <[string]>
+ - `value` <[string]>
+ - `domain` <[string]>
+ - `path` <[string]>
+ - `expires` <[float]> Unix time in seconds.
+ - `httpOnly` <[boolean]>
+ - `secure` <[boolean]>
+ - `sameSite` <[SameSiteAttribute]<"Strict"|"Lax"|"None">>
+ - `partitionKey` ?<[string]>
+
+If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+are returned. For [`property: BrowserContext.request`] and [`property: Page.request`], this is equivalent to calling
+[`method: BrowserContext.cookies`] on the corresponding browser context.
+
+### param: APIRequestContext.cookies.urls = %%-cookies-param-urls-%%
+* since: v1.64
+
## method: APIRequestContext.createFormData
* since: v1.23
* langs: csharp
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index b18de7eea9..1c36fc50b4 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -537,23 +537,14 @@ await context.ClearCookiesAsync(new() { Path = "/api/v1" });
await context.ClearCookiesAsync(new() { Name = "session-id", Domain = "my-origin.com" });
```
-### option: BrowserContext.clearCookies.name
+### option: BrowserContext.clearCookies.name = %%-clear-cookies-option-name-%%
* since: v1.43
-- `name` <[string]|[RegExp]>
-Only removes cookies with the given name.
-
-### option: BrowserContext.clearCookies.domain
+### option: BrowserContext.clearCookies.domain = %%-clear-cookies-option-domain-%%
* since: v1.43
-- `domain` <[string]|[RegExp]>
-
-Only removes cookies with the given domain.
-### option: BrowserContext.clearCookies.path
+### option: BrowserContext.clearCookies.path = %%-clear-cookies-option-path-%%
* since: v1.43
-- `path` <[string]|[RegExp]>
-
-Only removes cookies with the given path.
## async method: BrowserContext.clearPermissions
* since: v1.8
@@ -626,11 +617,8 @@ The default browser context cannot be closed.
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
are returned.
-### param: BrowserContext.cookies.urls
+### param: BrowserContext.cookies.urls = %%-cookies-param-urls-%%
* since: v1.8
-- `urls` ?<[string]|[Array]<[string]>>
-
-Optional list of URLs.
## async method: BrowserContext.exposeBinding
* since: v1.8
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 8611c5dc4c..2a8cee3fec 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -344,6 +344,26 @@ obtained via [`method: BrowserContext.storageState`]. Path to the file with save
- `sameSite` ?<[SameSiteAttribute]<"Strict"|"Lax"|"None">> Optional.
- `partitionKey` ?<[string]> For partitioned third-party cookies (aka [CHIPS](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Privacy_sandbox/Partitioned_cookies)), the partition key. Optional.
+## clear-cookies-option-name
+- `name` <[string]|[RegExp]>
+
+Only removes cookies with the given name.
+
+## clear-cookies-option-domain
+- `domain` <[string]|[RegExp]>
+
+Only removes cookies with the given domain.
+
+## clear-cookies-option-path
+- `path` <[string]|[RegExp]>
+
+Only removes cookies with the given path.
+
+## cookies-param-urls
+- `urls` ?<[string]|[Array]<[string]>>
+
+Optional list of URLs.
+
## storagestate-option-path
- `path` <[path]>
diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.ts
index 8025036634..9bfc1b85aa 100644
--- a/packages/isomorphic/protocolMetainfo.ts
+++ b/packages/isomorphic/protocolMetainfo.ts
@@ -50,6 +50,8 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([
['APIRequestContext.fetchResponseBody', { title: 'Get response body', group: 'getter', }],
['APIRequestContext.fetchLog', { internal: true, }],
['APIRequestContext.addCookies', { title: 'Add cookies', group: 'configuration', }],
+ ['APIRequestContext.clearCookies', { title: 'Clear cookies', group: 'configuration', }],
+ ['APIRequestContext.cookies', { title: 'Get cookies', group: 'getter', }],
['APIRequestContext.storageState', { title: 'Get storage state', group: 'configuration', }],
['APIRequestContext.disposeAPIResponse', { internal: true, }],
['APIRequestContext.dispose', { internal: true, }],
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index eef3801009..1724559292 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -19784,6 +19784,75 @@ export interface APIRequestContext {
partitionKey?: string;
}>): Promise<void>;
+ /**
+ * Removes cookies from this request context. Accepts optional filter. For
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request), this is equivalent to calling
+ * [browserContext.clearCookies([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-clear-cookies)
+ * on the corresponding browser context.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await request.clearCookies();
+ * await request.clearCookies({ name: 'session-id' });
+ * await request.clearCookies({ domain: 'my-origin.com' });
+ * await request.clearCookies({ domain: /.*my-origin\.com/ });
+ * await request.clearCookies({ path: '/api/v1' });
+ * await request.clearCookies({ name: 'session-id', domain: 'my-origin.com' });
+ * ```
+ *
+ * @param options
+ */
+ clearCookies(options?: {
+ /**
+ * Only removes cookies with the given domain.
+ */
+ domain?: string|RegExp;
+
+ /**
+ * Only removes cookies with the given name.
+ */
+ name?: string|RegExp;
+
+ /**
+ * Only removes cookies with the given path.
+ */
+ path?: string|RegExp;
+ }): Promise<void>;
+
+ /**
+ * If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
+ * URLs are returned. For
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request), this is equivalent to calling
+ * [browserContext.cookies([urls])](https://playwright.dev/docs/api/class-browsercontext#browser-context-cookies) on
+ * the corresponding browser context.
+ * @param urls Optional list of URLs.
+ */
+ cookies(urls?: string|ReadonlyArray<string>): Promise<Array<{
+ name: string;
+
+ value: string;
+
+ domain: string;
+
+ path: string;
+
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
+
+ httpOnly: boolean;
+
+ secure: boolean;
+
+ sameSite: "Strict"|"Lax"|"None";
+
+ partitionKey?: string;
+ }>>;
+
/**
* Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
* response. The method will populate request cookies from the context and update context cookies from the response.
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts
index 03ae7a5eb1..ddebc7b6c6 100644
--- a/packages/playwright-core/src/client/browserContext.ts
+++ b/packages/playwright-core/src/client/browserContext.ts
@@ -20,7 +20,6 @@ import path from 'path';
import { headersObjectToArray } from '@isomorphic/headers';
import { urlMatchesEqual } from '@isomorphic/urlMatch';
-import { isRegExp, isString } from '@isomorphic/rtti';
import { rewriteErrorMessage } from '@utils/stackTrace';
import { Browser } from './browser';
import { CDPSession } from './cdpSession';
@@ -331,17 +330,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
}
async clearCookies(options: network.ClearNetworkCookieOptions = {}): Promise<void> {
- await this._channel.clearCookies({
- name: isString(options.name) ? options.name : undefined,
- nameRegexSource: isRegExp(options.name) ? options.name.source : undefined,
- nameRegexFlags: isRegExp(options.name) ? options.name.flags : undefined,
- domain: isString(options.domain) ? options.domain : undefined,
- domainRegexSource: isRegExp(options.domain) ? options.domain.source : undefined,
- domainRegexFlags: isRegExp(options.domain) ? options.domain.flags : undefined,
- path: isString(options.path) ? options.path : undefined,
- pathRegexSource: isRegExp(options.path) ? options.path.source : undefined,
- pathRegexFlags: isRegExp(options.path) ? options.path.flags : undefined,
- }, kNoTimeout);
+ await this._channel.clearCookies(network.toClearCookiesParams(options), kNoTimeout);
}
async grantPermissions(permissions: string[], options?: { origin?: string }): Promise<void> {
diff --git a/packages/playwright-core/src/client/channels.d.ts b/packages/playwright-core/src/client/channels.d.ts
index 16e4ab0a86..b16202f1dd 100644
--- a/packages/playwright-core/src/client/channels.d.ts
+++ b/packages/playwright-core/src/client/channels.d.ts
@@ -590,6 +590,8 @@ export interface APIRequestContextChannel extends APIRequestContextEventTarget,
fetchResponseBody(params: APIRequestContextFetchResponseBodyParams, options: TimeoutOptions): Promise<APIRequestContextFetchResponseBodyResult>;
fetchLog(params: APIRequestContextFetchLogParams, options: TimeoutOptions): Promise<APIRequestContextFetchLogResult>;
addCookies(params: APIRequestContextAddCookiesParams, options: TimeoutOptions): Promise<APIRequestContextAddCookiesResult>;
+ clearCookies(params: APIRequestContextClearCookiesParams, options: TimeoutOptions): Promise<APIRequestContextClearCookiesResult>;
+ cookies(params: APIRequestContextCookiesParams, options: TimeoutOptions): Promise<APIRequestContextCookiesResult>;
storageState(params: APIRequestContextStorageStateParams, options: TimeoutOptions): Promise<APIRequestContextStorageStateResult>;
disposeAPIResponse(params: APIRequestContextDisposeAPIResponseParams, options: TimeoutOptions): Promise<APIRequestContextDisposeAPIResponseResult>;
dispose(params: APIRequestContextDisposeParams, options: TimeoutOptions): Promise<APIRequestContextDisposeResult>;
@@ -651,6 +653,38 @@ export type APIRequestContextAddCookiesOptions = {
};
export type APIRequestContextAddCookiesResult = void;
+export type APIRequestContextClearCookiesParams = {
+ name?: string,
+ nameRegexSource?: string,
+ nameRegexFlags?: string,
+ domain?: string,
+ domainRegexSource?: string,
+ domainRegexFlags?: string,
+ path?: string,
+ pathRegexSource?: string,
+ pathRegexFlags?: string,
+};
+export type APIRequestContextClearCookiesOptions = {
+ name?: string,
+ nameRegexSource?: string,
+ nameRegexFlags?: string,
+ domain?: string,
+ domainRegexSource?: string,
+ domainRegexFlags?: string,
+ path?: string,
+ pathRegexSource?: string,
+ pathRegexFlags?: string,
+};
+export type APIRequestContextClearCookiesResult = void;
+export type APIRequestContextCookiesParams = {
+ urls: string[],
+};
+export type APIRequestContextCookiesOptions = {
+
+};
+export type APIRequestContextCookiesResult = {
+ cookies: NetworkCookie[],
+};
export type APIRequestContextStorageStateParams = {
indexedDB?: boolean,
opfs?: boolean,
diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.ts
index deb94e5351..2915fa6dc5 100644
--- a/packages/playwright-core/src/client/fetch.ts
+++ b/packages/playwright-core/src/client/fetch.ts
@@ -24,13 +24,13 @@ import { isString } from '@isomorphic/rtti';
import { toClientCertificatesProtocol, toHttpCredentialsProtocol } from './browserContext';
import { ChannelOwner } from './channelOwner';
import { TargetClosedError, isTargetClosedError } from './errors';
-import { RawHeaders } from './network';
+import { RawHeaders, toClearCookiesParams } from './network';
import { Tracing } from './tracing';
import { mkdirIfNeeded } from './fileUtils';
import { TimeoutSettings, kNoTimeout } from './timeoutSettings';
import type { Playwright } from './playwright';
-import type { ResourceTiming, SetNetworkCookieParam } from './network';
+import type { ClearNetworkCookieOptions, NetworkCookie, ResourceTiming, SetNetworkCookieParam } from './network';
import type { ClientCertificate, FilePayload, Headers, RemoteAddr, SecurityDetails, SetStorageState, StorageState, TimeoutOptions } from './types';
import type { HttpCredentials } from '@protocol/structs';
import type { Serializable } from '../../types/structs';
@@ -128,10 +128,22 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextCh
this._request?._contexts.delete(this);
}
+ async cookies(urls?: string | string[]): Promise<NetworkCookie[]> {
+ if (!urls)
+ urls = [];
+ if (typeof urls === 'string')
+ urls = [urls];
+ return (await this._channel.cookies({ urls }, kNoTimeout)).cookies;
+ }
+
async addCookies(cookies: SetNetworkCookieParam[]): Promise<void> {
await this._channel.addCookies({ cookies }, kNoTimeout);
}
+ async clearCookies(options: ClearNetworkCookieOptions = {}): Promise<void> {
+ await this._channel.clearCookies(toClearCookiesParams(options), kNoTimeout);
+ }
+
async delete(url: string, options?: RequestWithBodyOptions): Promise<APIResponse> {
return await this.fetch(url, {
...options,
diff --git a/packages/playwright-core/src/client/network.ts b/packages/playwright-core/src/client/network.ts
index 82286526e8..52cad6aeeb 100644
--- a/packages/playwright-core/src/client/network.ts
+++ b/packages/playwright-core/src/client/network.ts
@@ -21,7 +21,7 @@ import { headersObjectToArray } from '@isomorphic/headers';
import { resolveGlobToRegexPattern, serializeURLMatch, urlMatches } from '@isomorphic/urlMatch';
import { LongStandingScope, ManualPromise } from '@isomorphic/manualPromise';
import { MultiMap } from '@isomorphic/multimap';
-import { isString } from '@isomorphic/rtti';
+import { isRegExp, isString } from '@isomorphic/rtti';
import { rewriteErrorMessage } from '@utils/stackTrace';
import { getMimeTypeForPath } from '@isomorphic/mimeType';
import { currentZone } from '@utils/zones';
@@ -73,6 +73,20 @@ export type ClearNetworkCookieOptions = {
path?: string | RegExp,
};
+export function toClearCookiesParams(options: ClearNetworkCookieOptions): channels.BrowserContextClearCookiesParams {
+ return {
+ name: isString(options.name) ? options.name : undefined,
+ nameRegexSource: isRegExp(options.name) ? options.name.source : undefined,
+ nameRegexFlags: isRegExp(options.name) ? options.name.flags : undefined,
+ domain: isString(options.domain) ? options.domain : undefined,
+ domainRegexSource: isRegExp(options.domain) ? options.domain.source : undefined,
+ domainRegexFlags: isRegExp(options.domain) ? options.domain.flags : undefined,
+ path: isString(options.path) ? options.path : undefined,
+ pathRegexSource: isRegExp(options.path) ? options.path.source : undefined,
+ pathRegexFlags: isRegExp(options.path) ? options.path.flags : undefined,
+ };
+}
+
type SerializedFallbackOverrides = {
url?: string;
method?: string;
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts
index 86a3ad3052..38134b7c5e 100644
--- a/packages/playwright-core/src/server/browserContext.ts
+++ b/packages/playwright-core/src/server/browserContext.ts
@@ -311,29 +311,14 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
return await this.doGetCookies(urls as string[]);
}
- async clearCookies(options: {name?: string | RegExp, domain?: string | RegExp, path?: string | RegExp}): Promise<void> {
- const hasFilter = options.name !== undefined || options.domain !== undefined || options.path !== undefined;
- if (!hasFilter) {
+ async clearCookies(options: network.ClearCookiesOptions): Promise<void> {
+ if (!network.hasClearCookiesFilter(options)) {
await this.doClearCookies();
return;
}
- const matches = (cookie: channels.NetworkCookie, prop: 'name' | 'domain' | 'path', value: string | RegExp | undefined) => {
- if (!value)
- return true;
- if (value instanceof RegExp) {
- value.lastIndex = 0;
- return value.test(cookie[prop]);
- }
- return cookie[prop] === value;
- };
-
const currentCookies = await this._cookies();
- const cookiesToExpire = currentCookies.filter(cookie => {
- return matches(cookie, 'name', options.name)
- && matches(cookie, 'domain', options.domain)
- && matches(cookie, 'path', options.path);
- });
+ const cookiesToExpire = currentCookies.filter(cookie => network.cookieMatchesClearFilter(cookie, options));
if (!cookiesToExpire.length)
return;
diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.ts
index 465b517b0a..dd7b4f8902 100644
--- a/packages/playwright-core/src/server/channels.d.ts
+++ b/packages/playwright-core/src/server/channels.d.ts
@@ -591,6 +591,8 @@ export interface APIRequestContextChannel extends APIRequestContextEventTarget,
fetchResponseBody(params: APIRequestContextFetchResponseBodyParams, progress: Progress): Promise<APIRequestContextFetchResponseBodyResult>;
fetchLog(params: APIRequestContextFetchLogParams, progress: Progress): Promise<APIRequestContextFetchLogResult>;
addCookies(params: APIRequestContextAddCookiesParams, progress: Progress): Promise<APIRequestContextAddCookiesResult>;
+ clearCookies(params: APIRequestContextClearCookiesParams, progress: Progress): Promise<APIRequestContextClearCookiesResult>;
+ cookies(params: APIRequestContextCookiesParams, progress: Progress): Promise<APIRequestContextCookiesResult>;
storageState(params: APIRequestContextStorageStateParams, progress: Progress): Promise<APIRequestContextStorageStateResult>;
disposeAPIResponse(params: APIRequestContextDisposeAPIResponseParams, progress: Progress): Promise<APIRequestContextDisposeAPIResponseResult>;
dispose(params: APIRequestContextDisposeParams, progress: Progress): Promise<APIRequestContextDisposeResult>;
@@ -652,6 +654,38 @@ export type APIRequestContextAddCookiesOptions = {
};
export type APIRequestContextAddCookiesResult = void;
+export type APIRequestContextClearCookiesParams = {
+ name?: string,
+ nameRegexSource?: string,
+ nameRegexFlags?: string,
+ domain?: string,
+ domainRegexSource?: string,
+ domainRegexFlags?: string,
+ path?: string,
+ pathRegexSource?: string,
+ pathRegexFlags?: string,
+};
+export type APIRequestContextClearCookiesOptions = {
+ name?: string,
+ nameRegexSource?: string,
+ nameRegexFlags?: string,
+ domain?: string,
+ domainRegexSource?: string,
+ domainRegexFlags?: string,
+ path?: string,
+ pathRegexSource?: string,
+ pathRegexFlags?: string,
+};
+export type APIRequestContextClearCookiesResult = void;
+export type APIRequestContextCookiesParams = {
+ urls: string[],
+};
+export type APIRequestContextCookiesOptions = {
+
+};
+export type APIRequestContextCookiesResult = {
+ cookies: NetworkCookie[],
+};
export type APIRequestContextStorageStateParams = {
indexedDB?: boolean,
opfs?: boolean,
diff --git a/packages/playwright-core/src/server/cookieStore.ts b/packages/playwright-core/src/server/cookieStore.ts
index 2e5fdd8fba..5d54b6032b 100644
--- a/packages/playwright-core/src/server/cookieStore.ts
+++ b/packages/playwright-core/src/server/cookieStore.ts
@@ -68,15 +68,6 @@ export class CookieStore {
this._addCookie(new Cookie(cookie));
}
- cookies(url: URL): channels.NetworkCookie[] {
- const result = [];
- for (const cookie of this._cookiesIterator()) {
- if (cookie.matches(url))
- result.push(cookie._networkCookie());
- }
- return result;
- }
-
allCookies(): channels.NetworkCookie[] {
const result = [];
for (const cookie of this._cookiesIterator())
@@ -84,6 +75,17 @@ export class CookieStore {
return result;
}
+ removeCookies(predicate: (cookie: channels.NetworkCookie) => boolean) {
+ for (const [name, cookies] of this._nameToCookies) {
+ for (const cookie of cookies) {
+ if (predicate(cookie._networkCookie()))
+ cookies.delete(cookie);
+ }
+ if (cookies.size === 0)
+ this._nameToCookies.delete(name);
+ }
+ }
+
private _addCookie(cookie: Cookie) {
let set = this._nameToCookies.get(cookie._name());
if (!set) {
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index 4a77725925..35b19a550f 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -26,7 +26,7 @@ import { DebuggerDispatcher } from './debuggerDispatcher';
import { DialogDispatcher } from './dialogDispatcher';
import { Dispatcher } from './dispatcher';
import { FrameDispatcher } from './frameDispatcher';
-import { APIRequestContextDispatcher, RequestDispatcher, ResponseDispatcher, RouteDispatcher } from './networkDispatchers';
+import { APIRequestContextDispatcher, RequestDispatcher, ResponseDispatcher, RouteDispatcher, parseClearCookiesParams } from './networkDispatchers';
import { BindingCallDispatcher, PageDispatcher, WorkerDispatcher } from './pageDispatcher';
import { CRBrowser, CRBrowserContext } from '../chromium/crBrowser';
import { serializeError } from '../errors';
@@ -275,14 +275,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
async clearCookies(params: channels.BrowserContextClearCookiesParams, progress: Progress): Promise<void> {
// Note: progress is ignored because this operation is not cancellable and should not block in the browser anyway.
- const nameRe = params.nameRegexSource !== undefined && params.nameRegexFlags !== undefined ? new RegExp(params.nameRegexSource, params.nameRegexFlags) : undefined;
- const domainRe = params.domainRegexSource !== undefined && params.domainRegexFlags !== undefined ? new RegExp(params.domainRegexSource, params.domainRegexFlags) : undefined;
- const pathRe = params.pathRegexSource !== undefined && params.pathRegexFlags !== undefined ? new RegExp(params.pathRegexSource, params.pathRegexFlags) : undefined;
- await progress.race(this._context.clearCookies({
- name: nameRe || params.name,
- domain: domainRe || params.domain,
- path: pathRe || params.path,
- }));
+ await progress.race(this._context.clearCookies(parseClearCookiesParams(params)));
}
async grantPermissions(params: channels.BrowserContextGrantPermissionsParams, 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 117b691ab2..13330e77c0 100644
--- a/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts
+++ b/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts
@@ -22,7 +22,7 @@ import { TracingDispatcher } from './tracingDispatcher';
import { Request } from '../network';
import type { APIRequestContext } from '../fetch';
-import type { Response, Route } from '../network';
+import type { ClearCookiesOptions, Response, Route } from '../network';
import type { BrowserContextDispatcher } from './browserContextDispatcher';
import type { RootDispatcher } from './dispatcher';
import type { PageDispatcher } from './pageDispatcher';
@@ -215,6 +215,14 @@ export class APIRequestContextDispatcher extends Dispatcher<APIRequestContext, c
await progress.race(this._object.addCookies(params.cookies));
}
+ async cookies(params: channels.APIRequestContextCookiesParams, progress: Progress): Promise<channels.APIRequestContextCookiesResult> {
+ return { cookies: await this._object.cookies(progress, params.urls) };
+ }
+
+ async clearCookies(params: channels.APIRequestContextClearCookiesParams, progress: Progress): Promise<void> {
+ await progress.race(this._object.clearCookies(parseClearCookiesParams(params)));
+ }
+
async storageState(params: channels.APIRequestContextStorageStateParams, progress: Progress): Promise<channels.APIRequestContextStorageStateResult> {
return await this._object.storageState(progress, params);
}
@@ -241,3 +249,14 @@ export class APIRequestContextDispatcher extends Dispatcher<APIRequestContext, c
this._object.disposeResponse(progress, params.fetchUid);
}
}
+
+export function parseClearCookiesParams(params: channels.BrowserContextClearCookiesParams | channels.APIRequestContextClearCookiesParams): ClearCookiesOptions {
+ const nameRe = params.nameRegexSource !== undefined && params.nameRegexFlags !== undefined ? new RegExp(params.nameRegexSource, params.nameRegexFlags) : undefined;
+ const domainRe = params.domainRegexSource !== undefined && params.domainRegexFlags !== undefined ? new RegExp(params.domainRegexSource, params.domainRegexFlags) : undefined;
+ const pathRe = params.pathRegexSource !== undefined && params.pathRegexFlags !== undefined ? new RegExp(params.pathRegexSource, params.pathRegexFlags) : undefined;
+ return {
+ name: nameRe || params.name,
+ domain: domainRe || params.domain,
+ path: pathRe || params.path,
+ };
+}
diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.ts
index fce4e650ef..08c8c8fa67 100644
--- a/packages/playwright-core/src/server/fetch.ts
+++ b/packages/playwright-core/src/server/fetch.ts
@@ -30,7 +30,7 @@ import { getUserAgent } from './userAgent';
import { BrowserContext, findMatchingHttpCredentials, verifyClientCertificates } from './browserContext';
import { Cookie, CookieStore, domainMatches, parseRawCookie } from './cookieStore';
import { MultipartFormData } from './formData';
-import { rewriteCookies } from './network';
+import { cookieMatchesClearFilter, filterCookies, rewriteCookies } from './network';
import { TargetClosedError } from './errors';
import { SdkObject } from './instrumentation';
import { isAbortError } from './progress';
@@ -41,6 +41,7 @@ import type net from 'net';
import type { Playwright } from './playwright';
import type { Progress } from './progress';
+import type { ClearCookiesOptions } from './network';
import type * as types from './types';
import type { HeadersArray, ProxySettings } from './types';
import type { HttpCredentials } from '@protocol/structs';
@@ -155,7 +156,8 @@ export abstract class APIRequestContext extends SdkObject {
abstract _defaultOptions(): FetchRequestOptions;
abstract addCookies(cookies: channels.SetNetworkCookie[]): Promise<void>;
- abstract cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]>;
+ abstract cookies(progress: Progress, urls: string[]): Promise<channels.NetworkCookie[]>;
+ abstract clearCookies(options: ClearCookiesOptions): Promise<void>;
protected _disposeImpl() {
this._disposed = true;
@@ -285,7 +287,7 @@ export abstract class APIRequestContext extends SdkObject {
private async _updateRequestCookieHeader(progress: Progress, url: URL, headers: HeadersObject) {
if (getHeader(headers, 'cookie') !== undefined)
return;
- const contextCookies = await this.cookies(progress, url);
+ const contextCookies = await this.cookies(progress, [url.toString()]);
// Browser context returns cookies with domain matching both .example.com and
// example.com. Those without leading dot are only sent when domain is strictly
// matching example.com, but not for sub.example.com.
@@ -733,8 +735,12 @@ export class BrowserContextAPIRequestContext extends APIRequestContext {
await this._context.addCookies(cookies);
}
- async cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]> {
- return await this._context.cookies(progress, url.toString());
+ async cookies(progress: Progress, urls: string[]): Promise<channels.NetworkCookie[]> {
+ return await this._context.cookies(progress, urls);
+ }
+
+ async clearCookies(options: ClearCookiesOptions): Promise<void> {
+ await this._context.clearCookies(options);
}
override async storageState(progress: Progress, params: { indexedDB?: boolean, opfs?: boolean }): Promise<channels.APIRequestContextStorageStateResult> {
@@ -797,8 +803,12 @@ export class GlobalAPIRequestContext extends APIRequestContext {
})));
}
- async cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]> {
- return this._cookieStore.cookies(url);
+ async cookies(progress: Progress, urls: string[]): Promise<channels.NetworkCookie[]> {
+ return filterCookies(this._cookieStore.allCookies(), urls);
+ }
+
+ async clearCookies(options: ClearCookiesOptions): Promise<void> {
+ this._cookieStore.removeCookies(cookie => cookieMatchesClearFilter(cookie, options));
}
override async storageState(progress: Progress, { indexedDB = false, opfs = false }: { indexedDB?: boolean, opfs?: boolean }): Promise<channels.APIRequestContextStorageStateResult> {
diff --git a/packages/playwright-core/src/server/network.ts b/packages/playwright-core/src/server/network.ts
index d25f342645..20bea1ec43 100644
--- a/packages/playwright-core/src/server/network.ts
+++ b/packages/playwright-core/src/server/network.ts
@@ -119,6 +119,25 @@ export function applyHeadersOverrides(original: HeadersArray, overrides: Headers
// 253402300800 == Sat, 1 Jan 1000 00:00:00 +0000 (UTC)
export const kMaxCookieExpiresDateInSeconds = 253402300799;
+export type ClearCookiesOptions = { name?: string | RegExp, domain?: string | RegExp, path?: string | RegExp };
+
+export function hasClearCookiesFilter(options: ClearCookiesOptions): boolean {
+ return options.name !== undefined || options.domain !== undefined || options.path !== undefined;
+}
+
+export function cookieMatchesClearFilter(cookie: channels.NetworkCookie, options: ClearCookiesOptions): boolean {
+ const matches = (prop: 'name' | 'domain' | 'path', value: string | RegExp | undefined) => {
+ if (!value)
+ return true;
+ if (value instanceof RegExp) {
+ value.lastIndex = 0;
+ return value.test(cookie[prop]);
+ }
+ return cookie[prop] === value;
+ };
+ return matches('name', options.name) && matches('domain', options.domain) && matches('path', options.path);
+}
+
export function rewriteCookies(cookies: channels.SetNetworkCookie[]): channels.SetNetworkCookie[] {
return cookies.map(c => {
assert(c.url || (c.domain && c.path), 'Cookie should have a url or a domain/path pair');
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index eef3801009..1724559292 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -19784,6 +19784,75 @@ export interface APIRequestContext {
partitionKey?: string;
}>): Promise<void>;
+ /**
+ * Removes cookies from this request context. Accepts optional filter. For
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request), this is equivalent to calling
+ * [browserContext.clearCookies([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-clear-cookies)
+ * on the corresponding browser context.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await request.clearCookies();
+ * await request.clearCookies({ name: 'session-id' });
+ * await request.clearCookies({ domain: 'my-origin.com' });
+ * await request.clearCookies({ domain: /.*my-origin\.com/ });
+ * await request.clearCookies({ path: '/api/v1' });
+ * await request.clearCookies({ name: 'session-id', domain: 'my-origin.com' });
+ * ```
+ *
+ * @param options
+ */
+ clearCookies(options?: {
+ /**
+ * Only removes cookies with the given domain.
+ */
+ domain?: string|RegExp;
+
+ /**
+ * Only removes cookies with the given name.
+ */
+ name?: string|RegExp;
+
+ /**
+ * Only removes cookies with the given path.
+ */
+ path?: string|RegExp;
+ }): Promise<void>;
+
+ /**
+ * If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
+ * URLs are returned. For
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request), this is equivalent to calling
+ * [browserContext.cookies([urls])](https://playwright.dev/docs/api/class-browsercontext#browser-context-cookies) on
+ * the corresponding browser context.
+ * @param urls Optional list of URLs.
+ */
+ cookies(urls?: string|ReadonlyArray<string>): Promise<Array<{
+ name: string;
+
+ value: string;
+
+ domain: string;
+
+ path: string;
+
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
+
+ httpOnly: boolean;
+
+ secure: boolean;
+
+ sameSite: "Strict"|"Lax"|"None";
+
+ partitionKey?: string;
+ }>>;
+
/**
* Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
* response. The method will populate request cookies from the context and update context cookies from the response.
diff --git a/packages/protocol/spec/api.yml b/packages/protocol/spec/api.yml
index 97a5de90f4..a80cc0568e 100644
--- a/packages/protocol/spec/api.yml
+++ b/packages/protocol/spec/api.yml
@@ -76,6 +76,32 @@ APIRequestContext:
type: array
items: SetNetworkCookie
+ clearCookies:
+ title: Clear cookies
+ group: configuration
+ parameters:
+ name: string?
+ nameRegexSource: string?
+ nameRegexFlags: string?
+ domain: string?
+ domainRegexSource: string?
+ domainRegexFlags: string?
+ path: string?
+ pathRegexSource: string?
+ pathRegexFlags: string?
+
+ cookies:
+ title: Get cookies
+ group: getter
+ parameters:
+ urls:
+ type: array
+ items: string
+ returns:
+ cookies:
+ type: array
+ items: NetworkCookie
+
storageState:
title: Get storage state
group: configuration
diff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.ts
index 36c1583bec..0e0c3caff0 100644
--- a/packages/protocol/src/validator.ts
+++ b/packages/protocol/src/validator.ts
@@ -333,6 +333,24 @@ scheme.APIRequestContextAddCookiesParams = tObject({
cookies: tArray(tType('SetNetworkCookie')),
});
scheme.APIRequestContextAddCookiesResult = tOptional(tObject({}));
+scheme.APIRequestContextClearCookiesParams = tObject({
+ name: tOptional(tString),
+ nameRegexSource: tOptional(tString),
+ nameRegexFlags: tOptional(tString),
+ domain: tOptional(tString),
+ domainRegexSource: tOptional(tString),
+ domainRegexFlags: tOptional(tString),
+ path: tOptional(tString),
+ pathRegexSource: tOptional(tString),
+ pathRegexFlags: tOptional(tString),
+});
+scheme.APIRequestContextClearCookiesResult = tOptional(tObject({}));
+scheme.APIRequestContextCookiesParams = tObject({
+ urls: tArray(tString),
+});
+scheme.APIRequestContextCookiesResult = tObject({
+ cookies: tArray(tType('NetworkCookie')),
+});
scheme.APIRequestContextStorageStateParams = tObject({
indexedDB: tOptional(tBoolean),
opfs: tOptional(tBoolean),
diff --git a/tests/library/browsercontext-fetch.spec.ts b/tests/library/browsercontext-fetch.spec.ts
index c1dc3a9b2e..adc2a9d87b 100644
--- a/tests/library/browsercontext-fetch.spec.ts
+++ b/tests/library/browsercontext-fetch.spec.ts
@@ -379,6 +379,32 @@ it('page.request.addCookies should add cookies to the browser context', async ({
expect((await page.evaluate(() => document.cookie)).split(';').map(s => s.trim()).sort()).toEqual(['a=b', 'c=d']);
});
+it('page.request.cookies should return browser context cookies', async ({ context, page, server }) => {
+ await context.addCookies([
+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },
+ { name: 'c', value: 'd', domain: 'example.com', path: '/' },
+ ]);
+ expect((await page.request.cookies()).map(c => c.name).sort()).toEqual(['a', 'c']);
+ expect((await page.request.cookies(server.EMPTY_PAGE)).map(c => c.name)).toEqual(['a']);
+ expect(await page.request.cookies(server.EMPTY_PAGE)).toEqual(await context.cookies(server.EMPTY_PAGE));
+});
+
+it('page.request.clearCookies should clear browser context cookies', async ({ context, page, server }) => {
+ await context.addCookies([
+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },
+ { name: 'c', value: 'd', url: server.EMPTY_PAGE },
+ ]);
+ await page.request.clearCookies({ name: 'a' });
+ expect((await context.cookies()).map(c => c.name)).toEqual(['c']);
+ await page.request.clearCookies();
+ expect(await context.cookies()).toEqual([]);
+ const [req] = await Promise.all([
+ server.waitForRequest('/empty.html'),
+ page.request.get(server.EMPTY_PAGE),
+ ]);
+ expect(req.headers.cookie).toBeUndefined();
+});
+
it('should preserve cookie order from Set-Cookie header', async ({ context, page, server, browserName, isLinux }) => {
it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23390' });
server.setRoute('/setcookie.html', (req, res) => {
diff --git a/tests/library/global-fetch-cookie.spec.ts b/tests/library/global-fetch-cookie.spec.ts
index 15b441e70c..149dc48a47 100644
--- a/tests/library/global-fetch-cookie.spec.ts
+++ b/tests/library/global-fetch-cookie.spec.ts
@@ -80,6 +80,66 @@ it('addCookies should validate cookies', async ({ request }) => {
expect(error.message).toContain('Cookie should have a url or a domain/path pair');
});
+it('cookies should return cookies filtered by urls', async ({ request, server }) => {
+ await request.addCookies([
+ { name: 'a', value: 'b', domain: 'localhost', path: '/' },
+ { name: 'c', value: 'd', domain: 'localhost', path: '/input' },
+ { name: 'e', value: 'f', domain: 'one.com', path: '/' },
+ { name: 'g', value: 'h', domain: 'two.com', path: '/', secure: true },
+ ]);
+ expect((await request.cookies()).map(c => c.name)).toEqual(['a', 'c', 'e', 'g']);
+ expect((await request.cookies(server.EMPTY_PAGE)).map(c => c.name)).toEqual(['a']);
+ expect((await request.cookies(`${server.PREFIX}/input/button.html`)).map(c => c.name)).toEqual(['a', 'c']);
+ expect((await request.cookies(['http://sub.one.com/', 'http://two.com/'])).map(c => c.name)).toEqual(['e']);
+ expect((await request.cookies(['http://sub.one.com/', 'https://two.com/'])).map(c => c.name)).toEqual(['e', 'g']);
+ expect(await request.cookies('http://other.com/')).toEqual([]);
+});
+
+it('cookies should include cookies from Set-Cookie header', async ({ request, server }) => {
+ server.setRoute('/setcookie.html', (req, res) => {
+ res.setHeader('Set-Cookie', ['a=b; HttpOnly; SameSite=Strict', 'c=d; path=/input']);
+ res.end();
+ });
+ await request.get(`${server.PREFIX}/setcookie.html`);
+ expect(await request.cookies()).toEqual([
+ { name: 'a', value: 'b', domain: 'localhost', path: '/', expires: -1, httpOnly: true, secure: false, sameSite: 'Strict' },
+ { name: 'c', value: 'd', domain: 'localhost', path: '/input', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax' },
+ ]);
+});
+
+it('clearCookies should remove all cookies', async ({ request, server }) => {
+ await request.addCookies([
+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },
+ { name: 'c', value: 'd', domain: 'one.com', path: '/' },
+ ]);
+ await request.clearCookies();
+ expect(await request.cookies()).toEqual([]);
+ const [serverRequest] = await Promise.all([
+ server.waitForRequest('/empty.html'),
+ request.get(server.EMPTY_PAGE),
+ ]);
+ expect(serverRequest.headers.cookie).toBeUndefined();
+});
+
+it('clearCookies should filter by name, domain and path', async ({ request }) => {
+ await request.addCookies([
+ { name: 'session', value: '1', domain: 'one.com', path: '/' },
+ { name: 'session', value: '2', domain: 'two.com', path: '/' },
+ { name: 'session', value: '3', domain: 'two.com', path: '/api' },
+ { name: 'other', value: '4', domain: 'one.com', path: '/' },
+ ]);
+ const values = async () => (await request.cookies()).map(c => c.value).sort();
+
+ await request.clearCookies({ name: 'session', domain: 'two.com', path: '/api' });
+ expect(await values()).toEqual(['1', '2', '4']);
+
+ await request.clearCookies({ domain: /one\.com$/ });
+ expect(await values()).toEqual(['2']);
+
+ await request.clearCookies({ name: /^sess/ });
+ expect(await values()).toEqual([]);
+});
+
it('should filter outgoing cookies by path', async ({ request, server }) => {
server.setRoute('/setcookie.html', (req, res) => {
res.setHeader('Set-Cookie', ['a=v; path=/input/subfolder', 'b=v; path=/input', 'c=v;']);