How to use addCookie() and getCookieNamed() in Selenium WebDriver

Most of all you are already aware about browser cookie. Basically cookie is piece of data that is stored in your browser. It is sent from website you visit and mostly it is used to recognize if user return to website again. In sort, It tracks your website navigation journey. Cookie consist of different parameters like name, value, expiry, path, etc. Here we will see how can we add cookie and get cookie from browser in selenium webdriver using addCookie() and getCookieNamed().

How addCookie() and getCookieNamed() Works?
package TestPack;

import java.util.Date;

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

public class testaddCookie {
 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("", exePath);
  WebDriver driver = new ChromeDriver();
  //Add cookie with name, value, domain, path, expiry, isSecure and isHTTPOnly.
  driver.manage().addCookie(new Cookie("Cookiename", "1589516354637%2F1", "", "/", new Date((2035-1900),05,07), false, true));
  //Get cookie detail from browser using cookie name.
  Cookie cookie1 = driver.manage().getCookieNamed("Cookiename");


Output : Cookiename=1589516354637%2F1; expires=Sun, 07 Jun 2020 12:00:00 IST; path=/;;secure;

In above example you can see that we created and add new cookie with different cookie parameters like cookie name, value, domain, path, expiry etc.. using addCookie(). It will add cookie for you. And getCookieNamed will get cookie detail for given name of cookie.

No comments:

Post a Comment