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;
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");
  
  //Selenium 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));
 
  //Selenium 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 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