SUBSCRIBE HERE TO GET POST UPDATES VIA EMAIL :

Delivered by FeedBurner

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;
import org.openqa.selenium.chrome.ChromeDriver;

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

}

Output : Cookiename=1589516354637%2F1; expires=Sun, 07 Jun 2020 12:00:00 IST; path=/; domain=.only-testing-blog.blogspot.com;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