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

Selenium webdriver add cookie and selenium webdriver get Cookie Named are very useful methods. 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. 

Sometimes you need selenium webdriver add cookie during your test. selenium add cookie can help you to add browser cookie manually. Here we will see how can we add cookie and get cookie from browser in selenium webdriver using addCookie() and getCookieNamed().

Example of Selenium addCookie() and Selenium getCookieNamed()

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();
  //Selenium 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));
  //Selenium 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 selenium add cookie java and Selenium get Cookie Named java 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