Handle Cookies 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.
  • It is used to add a cookie to the current browsing context.
  • The method addCookie() adds a cookie to the current domain, we may need to navigate to the targeted URL to set the domain.
  • If the cookie’s domain name is left blank, it is assumed that the cookie is meant for the domain of the current document.
  • In below code snippet, We create a new cookie and added it to cookies. We can get the cookie using getCookieNamed() method.
  • Click on this link to see Add Cookie article.

        @Test
	public void VerifyAddedCookie() {
	    driver.get("https://makeinjava.com");
    
         // We are passing parameters, name = CookieName and value=12345678
	    Cookie cookie = new Cookie("CookieName", "12345678");
	    driver.manage().addCookie(cookie);
	    Cookie newAddedCookie = driver.manage().getCookieNamed("CookieName");
	 
          // Verify the cookie value
	    assertEquals(newAddedCookie.getValue(), "12345678");
	}
  • SeleniumWebDriver API provides different methods for deleting cookies.
  1. driver.manage().deleteCookie(Cookie cookie);  --  delete a specific cookie
  2. driver.manage().deleteCookieNamed(String name); --  delete named cookie from the current domain
  3. driver.manage().deleteAllCookies();  --  delete all the cookies for the current domain

The method getCookies() returns Set of cookies for the current domain.


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

The method getCookieNamed(String name) returns cookie with a given name, or null if no cookie found with the given name.


driver.manage().getCookieNamed(String name);

Scroll to Top