Add Cookie

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

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 body is a JSON Object with a single cookie field whose value is a cookie object:

name

The name of the cookie. Required.

value

The cookie value. Required.

path Optional

The cookie path. Defaults to "/".

domain Optional

The domain the cookie is visible to. Defaults to the current browsing context's document domain.

secure Optional

Whether the cookie is a secure cookie. Defaults to false.

httpOnly Optional

Whether the cookie is an HTTP-only cookie. Defaults to false.

expiry Optional

When the cookie expires, specified in seconds since the Unix epoch. Must be a number in the 0 to 2^53 − 1 range. If omitted, the cookie is a session cookie.

sameSite Optional

The cookie's same-site policy. One of "Lax", "Strict", or "None".

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.

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.

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

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:

bash
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
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8

{"value":null}

Specifications

Specification
WebDriver
# add-cookie

Browser compatibility

See also