Home > Automation Testing > Handle cookies in Selenium

Handle cookies in Selenium

Cookie are information stored on computers.It contains name and value of the cookie along with name and value it stores other information like domain name, expiry date, path, secure and http only flags.

We are going to cover below topics in this article

  1. Use of get, add and delete operations in selenium
  2. Create new cookie using Cookie class.

Use of get, add and delete operations in selenium

Selenium allows to read/get, add and delete operation on cookies (ref WebDriver.Options ).

 

To Read/Get

  • getCookies() → return set of cookies (Set<Cookie>)
  • getNamedCookie(cookieName) → return cookie by name.

Java code for get operation:

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

Cookie cookie=driver.manage().getNamedCookie(cookieName); 

 

To Add

  • addCookie(cookie) → add cookie to current active session.

Java code for add cookie:

driver.manage().addCookie(cookie); 

 

To Delete

  • deleteAllCookies() → delete all cookies for current domain.
  • deleteCookie(cookie) → delete specific cookie.
  • deleteCookieNamed(cookieName) → delete cookie by name.

Java code to delete cookie(s):

driver.manage().deleteAllCookies(); 

driver.manage().deleteCookie(cookie); 

driver.manage().deleteCookieNamed(cookieName); 

 

Java Code:

 

 

Create new cookie and add to webdriver

 

Different parameterized constructors can be used to create cookie in selenium where name and value are mandatory.

  1. Cookie(String name, String value)
  2. Cookie(String name, String value, String path)
  3. Cookie(String name, String value, String path,Date expiry)
  4. Cookie(String name, String value, String domain, String path,Date expiry)
  5. Cookie(String name, String value, String domain, String path,Date expiry, boolean isSecure)
  6. Cookie(String name, String value, String domain, String path,Date expiry, boolean isSecure, boolean isHttpOnly)
This Article is TAGGED in . BOOKMARK THE permalink.

Avatar photo
Neeraj Vishwakarma
Senior QA Engineer Skills: Automation Testing, Manual Testing, STLC, Java, Selenium Webdriver, Protractor, Database Testing.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">