The Add Cookie command of the WebDriver API adds a single cookie to the cookie store associated with the current browsing context's active document. This is broadly equivalent to setting Document.cookie in JavaScript.
Syntax
| Method | URI template |
|---|---|
POST |
/session/{session id}/cookie |
URL parameters
session id- : Identifier of the session.
Payload
The input is a JSON object with a single cookie key whose value is a cookie object with the following fields:
name- : The name of the cookie.
value- : The cookie value.
path- : The cookie path. Defaults to
"/".
- : The cookie path. Defaults to
domain- : The domain the cookie is visible to. Defaults to the current browsing context's document domain.
secure- : Whether the cookie is a secure cookie. Defaults to
false.
- : Whether the cookie is a secure cookie. Defaults to
httpOnly- : Whether the cookie is an HTTP-only cookie. Defaults to
false.
- : Whether the cookie is an HTTP-only cookie. Defaults to
expiry- : The cookie's expiry time in seconds since the Unix epoch. This value must be a number in the 0 to 2^53 − 1 range. If omitted, the cookie is treated as a session cookie.
sameSite- : The cookie's same-site policy. Possible values include
"Lax","Strict", and"None". Defaults to"None"if omitted.
- : The cookie's same-site policy. Possible values include
Return value
null if successful.
Errors
Invalid argument- : The
cookieobject is missing, is not a JSON object, is missing a required field, or one of its fields does not meet the type or value constraints.
- : The
Invalid cookie domain- : Attempted to set a cookie on a domain that is different from the current browsing context's document domain.
No such window- : The
windowobject has been discarded, indicating that the tab or window has been closed.
- : The
Unable to set cookie- : The remote end was unable to add the cookie to the cookie store.
Unexpected alert open- : A user prompt, such as
window.alert, blocks execution of the command until it is dealt with.
- : A user prompt, such as
Invalid session id- : The specified session does not exist.
Examples
Adding a cookie
With a WebDriver server running on localhost:4444, assume an active session has navigated to https://example.org. To add a cookie, send the cookie object as the request payload, replacing ID with the sessionId from the New Session response:
curl -i -H "Content-Type: application/json" \
-d '{"cookie": {"name": "session_token", "value": "abc123", "secure": true, "sameSite": "Strict"}}' \
http://localhost:4444/session/ID/cookie
The server responds with a null value to indicate success:
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
{"value":null}
Specifications
Browser compatibility
See also
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
