Search code examples
javaselenium-webdriverselenium-chromedriver

Selenium org.openqa.selenium.InvalidCookieDomainException: invalid cookie domain


I'm using selenium-java to launch a Google Chrome window and load a website. I would like to add cookies to the session, but I get an exception: org.openqa.selenium.InvalidCookieDomainException

The Code:

import java.util.Date;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

    public static void main(String[] args) {
        Date tomorrow = new Date(new Date().getTime() + 24 * 3600 * 1000);
        Cookie cookie = new Cookie.Builder("lang", "en")
        .domain(".example.com")
        .expiresOn(tomorrow)
        .path("/")
        .build();
        driver.manage().addCookie(cookie);
        driver.get("http://example.com");
    }

The last line results in the invalid cookie domain exception.

I have tried multiple variations and different domains. What am I doing wrong here? Note: without adding the cookie, the webpage loads just fine.

Ubuntu, Chrome Version 126.0.6478.182, openjdk 21.0.3, org.seleniumhq.selenium;selenium-java;4.23.0


Solution

  • Try removing the dot at the beginning of the domain field. e.g. .domain(".example.com") should be .domain("example.com")

    In addition, you'll need to set the cookie after visiting the site. So call driver.manage().addCookie(cookie); after driver.get("http://example.com");

    This is required by the webdriver which validates that you are on the same domain you are setting the cookie for. See here: https://w3c.github.io/webdriver/#add-cookie