Saturday, December 5, 2026

Cookies in Selenium Java

Cookies in Selenium Java

In Selenium WebDriver, cookies are small pieces of data stored by a web browser. They are used to maintain user sessions, remember login information, store user preferences, and track user activity.

Selenium provides the Cookie class and WebDriver.manage().getCookies() methods to manage browser cookies.

Cookies in Selenium Java


1. Types of Cookies

Common cookie types include:

Cookie Type Description
Session Cookie Expires when the browser session ends.
Persistent Cookie Remains stored until its expiration date.
Secure Cookie Sent only over secure HTTPS connections.
HttpOnly Cookie Cannot be accessed through JavaScript.
SameSite Cookie Controls whether cookies are sent with cross-site requests.

2. Selenium Cookie Methods

Selenium provides the following methods to handle cookies.

Method Description
getCookies() Gets all cookies.
getCookieNamed() Gets a cookie using its name.
addCookie() Adds a new cookie.
deleteCookie() Deletes a specific cookie.
deleteCookieNamed() Deletes a cookie using its name.
deleteAllCookies() Deletes all cookies.

3. Get All Cookies

Use getCookies() to retrieve all cookies from the current browser session.

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Set;

public class GetAllCookies {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.example.com");

        Set<Cookie> cookies = driver.manage().getCookies();

        for (Cookie cookie : cookies) {

            System.out.println("Name: " + cookie.getName());
            System.out.println("Value: " + cookie.getValue());
            System.out.println("Domain: " + cookie.getDomain());
            System.out.println("Path: " + cookie.getPath());
            System.out.println("Expiry: " + cookie.getExpiry());
            System.out.println("Secure: " + cookie.isSecure());
            System.out.println("HttpOnly: " + cookie.isHttpOnly());

            System.out.println("----------------------");
        }

        driver.quit();
    }
}

4. Get a Specific Cookie

Use getCookieNamed() to retrieve a cookie by its name.

Cookie cookie = driver.manage().getCookieNamed("session_id");

if (cookie != null) {
    System.out.println("Cookie Name: " + cookie.getName());
    System.out.println("Cookie Value: " + cookie.getValue());
} else {
    System.out.println("Cookie not found");
}

5. Add a Cookie

Use addCookie() to add a new cookie to the browser.

import org.openqa.selenium.Cookie;

Cookie cookie = new Cookie("username", "Sumit");

driver.manage().addCookie(cookie);

System.out.println("Cookie added successfully");

Important: Navigate to the target domain before adding a cookie. You cannot add a cookie for an unrelated domain.

6. Add Cookie with Expiry, Domain and Path

You can use the Cookie.Builder class to create cookies with additional properties.

import org.openqa.selenium.Cookie;

import java.util.Date;

Cookie cookie = new Cookie.Builder("user", "Sumit")
        .domain("example.com")
        .path("/")
        .expiresOn(new Date(System.currentTimeMillis() + 86400000))
        .isSecure(true)
        .isHttpOnly(true)
        .build();

driver.manage().addCookie(cookie);

Here:

  • domain() – Specifies the cookie domain.
  • path() – Specifies the cookie path.
  • expiresOn() – Sets the expiration date.
  • isSecure() – Sets the Secure flag.
  • isHttpOnly() – Sets the HttpOnly flag.

7. Delete a Specific Cookie

Use deleteCookie() to delete a particular cookie.

Cookie cookie = driver.manage().getCookieNamed("username");

if (cookie != null) {
    driver.manage().deleteCookie(cookie);
    System.out.println("Cookie deleted successfully");
}

8. Delete Cookie by Name

Use deleteCookieNamed() to delete a cookie using its name.

driver.manage().deleteCookieNamed("username");

9. Delete All Cookies

Use deleteAllCookies() to remove all cookies associated with the current browser's current domain.

driver.manage().deleteAllCookies();

System.out.println("All cookies deleted successfully");

10. Complete Selenium Cookie Example

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Date;
import java.util.Set;

public class CookieHandling {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://www.example.com");

        // 1. Get all cookies
        Set<Cookie> cookies = driver.manage().getCookies();

        for (Cookie cookie : cookies) {
            System.out.println(cookie);
        }

        // 2. Add cookie
        Cookie newCookie = new Cookie.Builder("username", "Sumit")
                .domain("example.com")
                .path("/")
                .expiresOn(new Date(
                    System.currentTimeMillis() + 86400000))
                .build();

        driver.manage().addCookie(newCookie);

        // 3. Get specific cookie
        Cookie cookie = driver.manage()
                .getCookieNamed("username");

        System.out.println("Cookie: " + cookie);

        // 4. Delete specific cookie
        driver.manage().deleteCookieNamed("username");

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

        driver.quit();
    }
}

11. Real-Time Scenario: Login Without Entering Credentials

One common use of cookies in automation testing is maintaining a logged-in session.

Scenario:

  1. Login to the application manually or through the login API.
  2. Retrieve the authentication cookie.
  3. Store the cookie.
  4. Open a new browser session.
  5. Add the authentication cookie.
  6. Refresh the application.
  7. Verify whether the user is logged in.

Example:

// First browser session
driver.get("https://example.com");

// Retrieve authentication cookie
Cookie authCookie =
        driver.manage().getCookieNamed("auth_token");

// Store cookie information before closing the browser
driver.quit();

// Start a new browser session
WebDriver newDriver = new ChromeDriver();

newDriver.get("https://example.com");

// Add authentication cookie
if (authCookie != null) {
    newDriver.manage().addCookie(authCookie);
}

// Refresh application
newDriver.navigate().refresh();

// Verify logged-in status
System.out.println(newDriver.getCurrentUrl());

Note: The cookie must still be valid, and its domain, path, security and SameSite requirements must match the application. A new browser session does not automatically share cookies with the old one.

12. Important Interview Questions

Q1. What is a cookie in Selenium?

A cookie is a small piece of browser-stored data used to maintain sessions, authentication and user preferences.

Q2. How do you get all cookies in Selenium?

driver.manage().getCookies();

Q3. How do you get a specific cookie?

driver.manage().getCookieNamed("session_id");

Q4. How do you add a cookie?

driver.manage().addCookie(new Cookie("name", "value"));

Q5. How do you delete all cookies?

driver.manage().deleteAllCookies();

Q6. Can Selenium access HttpOnly cookies?

Yes. Selenium WebDriver can retrieve HttpOnly cookies through its cookie-management API, even though JavaScript cannot access them through document.cookie.

Q7. What is the difference between Session Storage, Local Storage and Cookies?

Feature Cookies Local Storage Session Storage
Storage Browser Browser Browser tab
Expiry Configurable Until deleted Until tab session ends
Server communication Automatically sent when applicable Not automatic Not automatic
Capacity Small Larger Larger
Selenium access Cookie API JavaScript JavaScript

Interview tip: Be comfortable with getCookies(), getCookieNamed(), addCookie(), deleteCookieNamed() and deleteAllCookies(). These are frequently useful in Selenium automation interviews.

No comments:

Post a Comment