Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:SeleniumHQ Selenium Cookie

From Leeroopedia
Revision as of 11:50, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/SeleniumHQ_Selenium_Cookie.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains WebDriver, Browser_Automation
Last Updated 2026-02-12 00:00 GMT

Overview

The Cookie class is a Java representation of an HTTP cookie used within the Selenium WebDriver framework for managing browser cookies during automated browser sessions.

Description

Cookie is a serializable, immutable data class in the org.openqa.selenium package that models an HTTP cookie as defined by the W3C WebDriver specification. It encapsulates all standard cookie attributes: name, value, domain, path, expiry, secure, httpOnly, and sameSite. The class provides multiple overloaded constructors for convenience, a nested Builder class for fluent construction, a validate() method to enforce constraints (e.g., name must not be empty or contain semicolons, domain must not include a port), a toJson() method that serializes the cookie to a Map<String, Object> following the W3C table for cookie conversion, and standard equals/hashCode based on name and value. Internally, the domain is stripped of any port suffix, the path defaults to "/" if null or empty, and the expiry date is truncated to second-level precision because the WebDriver protocol specifies expiry in seconds since the UTC epoch.

Usage

Use the Cookie class whenever you need to add, inspect, or manipulate browser cookies through the WebDriver API. Common scenarios include setting authentication tokens before navigating to a page, pre-populating session state, reading cookies returned by the browser via WebDriver.Options.getCookies(), and deleting specific cookies. The Builder inner class is preferred when constructing cookies with many optional attributes, as it avoids the ambiguity of multiple constructor overloads.

Code Reference

Source Location

Signature

public class Cookie implements Serializable {

    // Primary constructor (all attributes)
    public Cookie(
        String name,
        String value,
        @Nullable String domain,
        @Nullable String path,
        @Nullable Date expiry,
        boolean isSecure,
        boolean isHttpOnly,
        @Nullable String sameSite);

    // Convenience constructors
    public Cookie(String name, String value);
    public Cookie(String name, String value, String path);
    public Cookie(String name, String value, @Nullable String path, @Nullable Date expiry);
    public Cookie(String name, String value, @Nullable String domain, @Nullable String path, @Nullable Date expiry);
    public Cookie(String name, String value, @Nullable String domain, @Nullable String path, @Nullable Date expiry, boolean isSecure);
    public Cookie(String name, String value, @Nullable String domain, @Nullable String path, @Nullable Date expiry, boolean isSecure, boolean isHttpOnly);

    // Nested Builder class
    public static class Builder {
        public Builder(String name, String value);
        public Builder domain(@Nullable String host);
        public Builder path(@Nullable String path);
        public Builder expiresOn(@Nullable Date expiry);
        public Builder isSecure(boolean secure);
        public Builder isHttpOnly(boolean httpOnly);
        public Builder sameSite(@Nullable String sameSite);
        public Cookie build();
    }
}

Import

import org.openqa.selenium.Cookie;

I/O Contract

Inputs

Name Type Required Description
name String Yes The name of the cookie. Must not be null, empty, or contain a semicolon character.
value String Yes The value of the cookie. Must not be null.
domain @Nullable String No The domain the cookie is visible to. Any port suffix is automatically stripped. Must not contain a colon after processing.
path @Nullable String No The path the cookie is visible to. Defaults to "/" if null or empty.
expiry @Nullable Date No The cookie's expiration date. Truncated to second-level precision internally. Null means a session cookie.
isSecure boolean No Whether this cookie requires a secure (HTTPS) connection. Defaults to false.
isHttpOnly boolean No Whether this cookie is HTTP-only (inaccessible to client-side scripts). Defaults to false.
sameSite @Nullable String No The SameSite attribute of the cookie. Accepted values include "None", "Lax", and "Strict". Null means the attribute is not set.

Outputs

Name Type Description
getName() String Returns the cookie name.
getValue() String Returns the cookie value.
getDomain() @Nullable String Returns the domain the cookie is scoped to, or null if not set.
getPath() String Returns the path the cookie is scoped to (always at least "/").
getExpiry() @Nullable Date Returns a defensive copy of the expiry date, or null for session cookies.
isSecure() boolean Returns whether the cookie requires a secure connection.
isHttpOnly() boolean Returns whether the cookie is HTTP-only.
getSameSite() @Nullable String Returns the SameSite attribute value, or null if not set.
toJson() Map<String, Object> Serializes the cookie to a sorted map following the W3C WebDriver cookie conversion table. Null fields are omitted.
toString() String Returns a Set-Cookie-style string representation (e.g., name=value; expires=...; path=/; domain=...).
validate() void Throws IllegalArgumentException if the cookie has invalid state (null/empty name, null value, semicolon in name, or port in domain).

Usage Examples

Basic Cookie Creation

// Create a simple session cookie with name and value
Cookie sessionCookie = new Cookie("session_id", "abc123");
driver.manage().addCookie(sessionCookie);

// Create a cookie with a specific path and expiry
Date tomorrow = new Date(System.currentTimeMillis() + 86400 * 1000);
Cookie pathCookie = new Cookie("prefs", "dark_mode", "/settings", tomorrow);
driver.manage().addCookie(pathCookie);

Using the Builder Pattern

// Build a fully-configured cookie using the fluent Builder API
Cookie cookie = new Cookie.Builder("auth_token", "eyJhbGciOiJIUzI1NiJ9")
    .domain(".example.com")
    .path("/")
    .expiresOn(new Date(System.currentTimeMillis() + 3600 * 1000))
    .isSecure(true)
    .isHttpOnly(true)
    .sameSite("Strict")
    .build();

driver.manage().addCookie(cookie);

Reading and Deleting Cookies

// Retrieve a cookie by name
Cookie existing = driver.manage().getCookieNamed("session_id");
if (existing != null) {
    System.out.println("Cookie value: " + existing.getValue());
    System.out.println("Cookie domain: " + existing.getDomain());
    System.out.println("Is secure: " + existing.isSecure());
}

// Delete a specific cookie
driver.manage().deleteCookieNamed("session_id");

// Delete all cookies
driver.manage().deleteAllCookies();

Serializing a Cookie to JSON

// Convert a cookie to its W3C JSON representation
Cookie cookie = new Cookie.Builder("tracking", "xyz789")
    .domain(".example.com")
    .path("/")
    .isSecure(true)
    .sameSite("Lax")
    .build();

Map<String, Object> json = cookie.toJson();
// Result: {domain=.example.com, httpOnly=false, name=tracking, path=/, sameSite=Lax, secure=true, value=xyz789}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment