Add a Cookie using Selenium WebDriver

  • A cookie is a small piece of data that is sent from a website and stored in your computer. Cookies are used to authenticate the user and load the stored information.
  • We can interact with cookie using WebDriver API built-in methods.
  • The method addCookie() adds a cookie to the current domain, we may need to navigate to the targeted URL to set the domain.

package TestCases;

import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class MakeinJavaTest {
	public WebDriver driver;

	@Test
	public void VerifyAddedCookie() {

		System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe");
		driver = new ChromeDriver();

		driver.get("https://makeinjava.com");
		// We are passing parameters, name = CookieName and value=12345678
		Cookie cookie = new Cookie("CookieName", "12345678");
		driver.manage().addCookie(cookie);

		// Display all the cookies on Console
		Set cookieList = driver.manage().getCookies();
		for (Cookie newCookie : cookieList) {
			System.out.println(newCookie);
		}

	}

}

Add Cookie using Selenium WebDriver Java

 

Scroll to Top