Cookies in selenium


  • Cookie is a piece  of information from website and saved by your web browser
  • Cookies are a way of remembering users and their interaction with the site by storing information in the cookie file as key value pairs.
  • It stores the login information like user name / email and password
  • HTTP cookie is also known as a web cookie, a browser cookie or Internet cookie.
  • One website cannot access the cookies set by other websites


Handling Cookie in Selenium :

  • Each cookie is associated with a name, value, domain, path, termination, and status of whether it is safe or not. We validate the cookie using selenium,  selenium can parse all the cookies
  • When testing a web application using the Selenium, you may need to create, update or delete a cookie to check the behavior of the website with and without cookies.
  • For example, when you automate e-commerce sites, you will set cookies for logins, products added to carts using cookies and the product you visited in or searched in past days


Get Cookies:

getCookies() used to return the list of all cookies stored in the web browser.

// fetch gets all the cookies
public Set<Cookie> getAllCookiesExample() {
        return driver.manage().getCookies();


Get Cookie by name:

getCookieNamed() used to return the specific cookie according to its name.

//fetchs a specified cookie
public Cookie getCookieNamedExample(String name) {
        return driver.manage().getCookieNamed(name);


Retrieve the value of a cookie:

// fetch the value of a specified cookie
public String getValueOfCookieNamedExample(String name) {
        return driver.manage().getCookieNamed(name).getValue();


Add Cookie:

addCookie() method is used to create and add the cookie.

// set or create a cookie
public void addCookieExample(String name, String value, String domain, String path, Date expiry) {
        new Cookie(name, value, domain, path, expiry));


Add a set of cookies:

//This method adds set of cookies for a domain
public void addCookiesToBrowserExample(Set<Cookie> cookies, String domain) {
        for (Cookie c : cookies) {
            if (c != null) {
                if (c.getDomain().contains(domain)){
                    new Cookie(name, value, domain, path, expiry));


Delete Cookie:

Using deleteCookie() we can delete a specific cookie, with Cookie object.

manage().deleteCookie(Cookie cookieObject);


Delete Cookie by name:

Using deleteCookieNamed() to delete a cookie according to its name.

//This method deletes a specific cookie
public void deleteCookieNamedExample(String name) {


Delete All Cookie:

deleteAllCookies() is used to delete all cookies.

//This method deletes all cookies
public void deleteAllCookiesExample() {






Leave a Reply

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