MDN self-hosted library · e01.org

Add Cookie

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.

no runnable cells webdriver-command upstream source

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 "/".
  • 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.
  • httpOnly
  • : Whether the cookie is an HTTP-only cookie. Defaults to false.
  • 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.

Return value

null if successful.

Errors

  • Invalid argument
  • : The cookie object 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.
  • 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 window object has been discarded, indicating that the tab or window has been closed.
  • 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.
  • Invalid session id
  • : The specified session does not exist.

Examples

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