How do I send cookies with Selenium WebDriver?

How do I send cookies with Selenium WebDriver?

Sending cookies with Selenium WebDriver can be achieved using the addCookie() method:

WebDriver driver = new ChromeDriver();
Cookie cookie = new Cookie("cookieName", "cookieValue");
driver.manage().addCookie(cookie);
driver.get("https://example.com");

This method uses the addCookie() method of the WebDriver.Options interface to add a cookie to the browser’s cookie jar. It’s a straightforward approach and works well for adding individual cookies.

You can also Cookie class directly:

WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Cookie cookie = new Cookie.Builder("cookieName", "cookieValue")
.domain("example.com")
.build();
driver.manage().addCookie(cookie);
driver.navigate().refresh();

This method allows you to create a Cookie object with more detailed settings, such as domain, path, expiry, etc. It provides more flexibility in managing cookies but requires more manual configuration.

Using the addCookie() method with a Map of cookie parameters:

WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Map<String, Object> cookieParams = new HashMap<>();
cookieParams.put("name", "cookieName");
cookieParams.put("value", "cookieValue");
driver.manage().addCookie(cookieParams);
driver.navigate().refresh();

This method uses a Map to specify cookie parameters, which can be more convenient when adding multiple cookies or when you need to set additional parameters like domain, path, etc.