Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(api): add APIRequestContext.addCookies (#43032)
Yury Semikhatsky2bb76e1b72e6
diff --git a/docs/src/api/class-apirequestcontext.md b/docs/src/api/class-apirequestcontext.mdindex 0adb320d9c..a977960c04 100644--- a/docs/src/api/class-apirequestcontext.md+++ b/docs/src/api/class-apirequestcontext.md@@ -124,6 +124,37 @@ with sync_playwright() as p:assert await response.body() == '{"status": "ok"}'```+## async method: APIRequestContext.addCookies+* since: v1.64++Adds cookies into this request context. They will be sent with matching subsequent requests. For [`property: BrowserContext.request`]+and [`property: Page.request`], this is equivalent to calling [`method: BrowserContext.addCookies`] on the corresponding browser context.++**Usage**++```js+await request.addCookies([cookieObject1, cookieObject2]);+```++```java+request.addCookies(Arrays.asList(cookieObject1, cookieObject2));+```++```python async+await request.add_cookies([cookie_object1, cookie_object2])+```++```python sync+request.add_cookies([cookie_object1, cookie_object2])+```++```csharp+await request.AddCookiesAsync(new[] { cookie1, cookie2 });+```++### param: APIRequestContext.addCookies.cookies = %%-add-cookies-param-%%+* since: v1.64+## method: APIRequestContext.createFormData* since: v1.23* langs: csharpdiff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.mdindex 1aa95f63d8..5528616186 100644--- a/docs/src/api/class-browsercontext.md+++ b/docs/src/api/class-browsercontext.md@@ -377,20 +377,8 @@ browser_context.add_cookies([cookie_object1, cookie_object2])await context.AddCookiesAsync(new[] { cookie1, cookie2 });```-### param: BrowserContext.addCookies.cookies+### param: BrowserContext.addCookies.cookies = %%-add-cookies-param-%%* since: v1.8-- `cookies` <[Array]<[Object]>>- * alias-java: Cookie- - `name` <[string]>- - `value` <[string]>- - `url` ?<[string]> Either `url` or both `domain` and `path` are required. Optional.- - `domain` ?<[string]> For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either `url` or both `domain` and `path` are required. Optional.- - `path` ?<[string]> Either `url` or both `domain` and `path` are required. Optional.- - `expires` ?<[float]> Unix time in seconds. Optional.- - `httpOnly` ?<[boolean]> Optional.- - `secure` ?<[boolean]> Optional.- - `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.## async method: BrowserContext.addInitScript* since: v1.8diff --git a/docs/src/api/params.md b/docs/src/api/params.mdindex e8e4080e1e..c08ec6ded3 100644--- a/docs/src/api/params.md+++ b/docs/src/api/params.md@@ -330,6 +330,20 @@ obtained via [`method: BrowserContext.storageState`].Populates context with given storage state. This option can be used to initialize context with logged-in informationobtained via [`method: BrowserContext.storageState`]. Path to the file with saved storage state.+## add-cookies-param+- `cookies` <[Array]<[Object]>>+ * alias-java: Cookie+ - `name` <[string]>+ - `value` <[string]>+ - `url` ?<[string]> Either `url` or both `domain` and `path` are required. Optional.+ - `domain` ?<[string]> For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either `url` or both `domain` and `path` are required. Optional.+ - `path` ?<[string]> Either `url` or both `domain` and `path` are required. Optional.+ - `expires` ?<[float]> Unix time in seconds. Optional.+ - `httpOnly` ?<[boolean]> Optional.+ - `secure` ?<[boolean]> Optional.+ - `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.+## storagestate-option-path- `path` <[path]>diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.tsindex 684aee3296..8025036634 100644--- a/packages/isomorphic/protocolMetainfo.ts+++ b/packages/isomorphic/protocolMetainfo.ts@@ -49,6 +49,7 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([['APIRequestContext.fetch', { title: '{method}', subtitle: '{url}', renderParams: ['url', 'method'], }],['APIRequestContext.fetchResponseBody', { title: 'Get response body', group: 'getter', }],['APIRequestContext.fetchLog', { internal: true, }],+ ['APIRequestContext.addCookies', { title: 'Add cookies', group: 'configuration', }],['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.tsindex b7ea37f78e..561dd5dbeb 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -19718,6 +19718,70 @@ export interface APIRequest {* `APIRequestContext` object will have its own isolated cookie storage.*/export interface APIRequestContext {+ /**+ * Adds cookies into this request context. They will be sent with matching subsequent requests. 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.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies)+ * on the corresponding browser context.+ *+ * **Usage**+ *+ * ```js+ * await request.addCookies([cookieObject1, cookieObject2]);+ * ```+ *+ * @param cookies+ */+ addCookies(cookies: ReadonlyArray<{+ name: string;++ value: string;++ /**+ * Either `url` or both `domain` and `path` are required. Optional.+ */+ url?: string;++ /**+ * For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either+ * `url` or both `domain` and `path` are required. Optional.+ */+ domain?: string;++ /**+ * Either `url` or both `domain` and `path` are required. Optional.+ */+ path?: string;++ /**+ * Unix time in seconds. Optional.+ */+ expires?: number;++ /**+ * Optional.+ */+ httpOnly?: boolean;++ /**+ * Optional.+ */+ secure?: boolean;++ /**+ * Optional.+ */+ sameSite?: "Strict"|"Lax"|"None";++ /**+ * 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.+ */+ partitionKey?: string;+ }>): Promise<void>;+/*** 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/channels.d.ts b/packages/playwright-core/src/client/channels.d.tsindex 91c4df4d4f..7e0b2a868f 100644--- a/packages/playwright-core/src/client/channels.d.ts+++ b/packages/playwright-core/src/client/channels.d.ts@@ -589,6 +589,7 @@ export interface APIRequestContextChannel extends APIRequestContextEventTarget,fetch(params: APIRequestContextFetchParams, options: TimeoutOptions): Promise<APIRequestContextFetchResult>;fetchResponseBody(params: APIRequestContextFetchResponseBodyParams, options: TimeoutOptions): Promise<APIRequestContextFetchResponseBodyResult>;fetchLog(params: APIRequestContextFetchLogParams, options: TimeoutOptions): Promise<APIRequestContextFetchLogResult>;+ addCookies(params: APIRequestContextAddCookiesParams, options: TimeoutOptions): Promise<APIRequestContextAddCookiesResult>;storageState(params: APIRequestContextStorageStateParams, options: TimeoutOptions): Promise<APIRequestContextStorageStateResult>;disposeAPIResponse(params: APIRequestContextDisposeAPIResponseParams, options: TimeoutOptions): Promise<APIRequestContextDisposeAPIResponseResult>;dispose(params: APIRequestContextDisposeParams, options: TimeoutOptions): Promise<APIRequestContextDisposeResult>;@@ -643,6 +644,13 @@ export type APIRequestContextFetchLogOptions = {export type APIRequestContextFetchLogResult = {log: string[],};+export type APIRequestContextAddCookiesParams = {+ cookies: SetNetworkCookie[],+};+export type APIRequestContextAddCookiesOptions = {++};+export type APIRequestContextAddCookiesResult = void;export type APIRequestContextStorageStateParams = {indexedDB?: boolean,opfs?: boolean,diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.tsindex 415568750e..deb94e5351 100644--- a/packages/playwright-core/src/client/fetch.ts+++ b/packages/playwright-core/src/client/fetch.ts@@ -30,7 +30,7 @@ import { mkdirIfNeeded } from './fileUtils';import { TimeoutSettings, kNoTimeout } from './timeoutSettings';import type { Playwright } from './playwright';-import type { ResourceTiming } from './network';+import type { 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,6 +128,10 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextChthis._request?._contexts.delete(this);}+ async addCookies(cookies: SetNetworkCookieParam[]): Promise<void> {+ await this._channel.addCookies({ cookies }, kNoTimeout);+ }+async delete(url: string, options?: RequestWithBodyOptions): Promise<APIResponse> {return await this.fetch(url, {...options,diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.tsindex f9ff479a4f..44cc79099d 100644--- a/packages/playwright-core/src/server/channels.d.ts+++ b/packages/playwright-core/src/server/channels.d.ts@@ -590,6 +590,7 @@ export interface APIRequestContextChannel extends APIRequestContextEventTarget,fetch(params: APIRequestContextFetchParams, progress: Progress): Promise<APIRequestContextFetchResult>;fetchResponseBody(params: APIRequestContextFetchResponseBodyParams, progress: Progress): Promise<APIRequestContextFetchResponseBodyResult>;fetchLog(params: APIRequestContextFetchLogParams, progress: Progress): Promise<APIRequestContextFetchLogResult>;+ addCookies(params: APIRequestContextAddCookiesParams, progress: Progress): Promise<APIRequestContextAddCookiesResult>;storageState(params: APIRequestContextStorageStateParams, progress: Progress): Promise<APIRequestContextStorageStateResult>;disposeAPIResponse(params: APIRequestContextDisposeAPIResponseParams, progress: Progress): Promise<APIRequestContextDisposeAPIResponseResult>;dispose(params: APIRequestContextDisposeParams, progress: Progress): Promise<APIRequestContextDisposeResult>;@@ -644,6 +645,13 @@ export type APIRequestContextFetchLogOptions = {export type APIRequestContextFetchLogResult = {log: string[],};+export type APIRequestContextAddCookiesParams = {+ cookies: SetNetworkCookie[],+};+export type APIRequestContextAddCookiesOptions = {++};+export type APIRequestContextAddCookiesResult = void;export type APIRequestContextStorageStateParams = {indexedDB?: boolean,opfs?: boolean,diff --git a/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts b/packages/playwright-core/src/server/dispatchers/networkDispatchers.tsindex 8e4f5b8bb0..117b691ab2 100644--- a/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts+++ b/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts@@ -211,6 +211,10 @@ export class APIRequestContextDispatcher extends Dispatcher<APIRequestContext, cthis.adopt(tracing);}+ async addCookies(params: channels.APIRequestContextAddCookiesParams, progress: Progress): Promise<void> {+ await progress.race(this._object.addCookies(params.cookies));+ }+async storageState(params: channels.APIRequestContextStorageStateParams, progress: Progress): Promise<channels.APIRequestContextStorageStateResult> {return await this._object.storageState(progress, params);}diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.tsindex c7bb3a8c53..fce4e650ef 100644--- a/packages/playwright-core/src/server/fetch.ts+++ b/packages/playwright-core/src/server/fetch.ts@@ -30,6 +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 { TargetClosedError } from './errors';import { SdkObject } from './instrumentation';import { isAbortError } from './progress';@@ -153,7 +154,7 @@ export abstract class APIRequestContext extends SdkObject {abstract dispose(options: { reason?: string }): Promise<void>;abstract _defaultOptions(): FetchRequestOptions;- abstract addCookies(cookies: channels.NetworkCookie[]): Promise<void>;+ abstract addCookies(cookies: channels.SetNetworkCookie[]): Promise<void>;abstract cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]>;protected _disposeImpl() {@@ -728,7 +729,7 @@ export class BrowserContextAPIRequestContext extends APIRequestContext {};}- async addCookies(cookies: channels.NetworkCookie[]): Promise<void> {+ async addCookies(cookies: channels.SetNetworkCookie[]): Promise<void> {await this._context.addCookies(cookies);}@@ -784,8 +785,16 @@ export class GlobalAPIRequestContext extends APIRequestContext {return this._options;}- async addCookies(cookies: channels.NetworkCookie[]): Promise<void> {- this._cookieStore.addCookies(cookies);+ async addCookies(cookies: channels.SetNetworkCookie[]): Promise<void> {+ this._cookieStore.addCookies(rewriteCookies(cookies).map(c => ({+ expires: -1,+ httpOnly: false,+ secure: false,+ sameSite: 'Lax',+ ...c,+ domain: c.domain!,+ path: c.path!,+ })));}async cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]> {diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex b7ea37f78e..561dd5dbeb 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -19718,6 +19718,70 @@ export interface APIRequest {* `APIRequestContext` object will have its own isolated cookie storage.*/export interface APIRequestContext {+ /**+ * Adds cookies into this request context. They will be sent with matching subsequent requests. 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.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies)+ * on the corresponding browser context.+ *+ * **Usage**+ *+ * ```js+ * await request.addCookies([cookieObject1, cookieObject2]);+ * ```+ *+ * @param cookies+ */+ addCookies(cookies: ReadonlyArray<{+ name: string;++ value: string;++ /**+ * Either `url` or both `domain` and `path` are required. Optional.+ */+ url?: string;++ /**+ * For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either+ * `url` or both `domain` and `path` are required. Optional.+ */+ domain?: string;++ /**+ * Either `url` or both `domain` and `path` are required. Optional.+ */+ path?: string;++ /**+ * Unix time in seconds. Optional.+ */+ expires?: number;++ /**+ * Optional.+ */+ httpOnly?: boolean;++ /**+ * Optional.+ */+ secure?: boolean;++ /**+ * Optional.+ */+ sameSite?: "Strict"|"Lax"|"None";++ /**+ * 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.+ */+ partitionKey?: string;+ }>): Promise<void>;+/*** 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.ymlindex f8ef4aae2c..97a5de90f4 100644--- a/packages/protocol/spec/api.yml+++ b/packages/protocol/spec/api.yml@@ -68,6 +68,14 @@ APIRequestContext:type: arrayitems: string+ addCookies:+ title: Add cookies+ group: configuration+ parameters:+ cookies:+ type: array+ items: SetNetworkCookie+storageState:title: Get storage stategroup: configurationdiff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.tsindex 81b4f86a51..a1a8a1488e 100644--- a/packages/protocol/src/validator.ts+++ b/packages/protocol/src/validator.ts@@ -329,6 +329,10 @@ scheme.APIRequestContextFetchLogParams = tObject({scheme.APIRequestContextFetchLogResult = tObject({log: tArray(tString),});+scheme.APIRequestContextAddCookiesParams = tObject({+ cookies: tArray(tType('SetNetworkCookie')),+});+scheme.APIRequestContextAddCookiesResult = tOptional(tObject({}));scheme.APIRequestContextStorageStateParams = tObject({indexedDB: tOptional(tBoolean),opfs: tOptional(tBoolean),diff --git a/tests/library/browsercontext-fetch.spec.ts b/tests/library/browsercontext-fetch.spec.tsindex 64d54e58dc..c1dc3a9b2e 100644--- a/tests/library/browsercontext-fetch.spec.ts+++ b/tests/library/browsercontext-fetch.spec.ts@@ -361,6 +361,24 @@ it('should add cookies from Set-Cookie header', async ({ context, page, server }expect((await page.evaluate(() => document.cookie)).split(';').map(s => s.trim()).sort()).toEqual(['foo=bar', 'session=value']);});+it('page.request.addCookies should add cookies to the browser context', async ({ context, page, server }) => {+ await page.request.addCookies([+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },+ { name: 'c', value: 'd', domain: 'localhost', path: '/', expires: Date.now() / 1000 + 3600 },+ ]);+ expect((await context.cookies()).map(c => ({ name: c.name, value: c.value })).sort((a, b) => a.name.localeCompare(b.name))).toEqual([+ { name: 'a', value: 'b' },+ { name: 'c', value: 'd' },+ ]);+ const [req] = await Promise.all([+ server.waitForRequest('/empty.html'),+ context.request.get(server.EMPTY_PAGE),+ ]);+ expect(req.headers.cookie.split(';').map(s => s.trim()).sort()).toEqual(['a=b', 'c=d']);+ await page.goto(server.EMPTY_PAGE);+ expect((await page.evaluate(() => document.cookie)).split(';').map(s => s.trim()).sort()).toEqual(['a=b', 'c=d']);+});+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.tsindex 32d8b58dfc..15b441e70c 100644--- a/tests/library/global-fetch-cookie.spec.ts+++ b/tests/library/global-fetch-cookie.spec.ts@@ -56,6 +56,30 @@ it('should store cookie from Set-Cookie header', async ({ request, server }) =>expect(serverRequest.headers.cookie).toBe('c=d');});+it('addCookies should add cookies to the cookie jar', async ({ request, server }) => {+ await request.addCookies([+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },+ { name: 'c', value: 'd', domain: 'localhost', path: '/input', httpOnly: true, sameSite: 'Strict' },+ { name: 'e', value: 'f', domain: 'other.com', path: '/' },+ ]);+ const [serverRequest] = await Promise.all([+ server.waitForRequest('/input/button.html'),+ request.get(`${server.PREFIX}/input/button.html`)+ ]);+ expect(serverRequest.headers.cookie).toBe('a=b; c=d');+ const state = await request.storageState();+ expect(state.cookies).toEqual([+ { name: 'a', value: 'b', domain: 'localhost', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax' },+ { name: 'c', value: 'd', domain: 'localhost', path: '/input', expires: -1, httpOnly: true, secure: false, sameSite: 'Strict' },+ { name: 'e', value: 'f', domain: 'other.com', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax' },+ ]);+});++it('addCookies should validate cookies', async ({ request }) => {+ const error = await request.addCookies([{ name: 'a', value: 'b' }]).catch(e => e);+ expect(error.message).toContain('Cookie should have a url or a domain/path pair');+});+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;']);