How to Create, Update and Delete Browser Cookies in Selenium WebDriver

HTTP Cookie is comprised of information about the user and their preferences. 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 is a small piece of data sent from Web Application and stored in Web Browser and when a user accesses the same website again, the browser sends back the stored cookie to the web server that notifies it about the user’s past activities.

Before using cookies in your code, first import the selenium cookies class

import org.openqa.selenium.Cookie;

Get all the cookies

//This method is to get all the cookies
public Set<Cookie> getAllCookies() {
    return driver.manage().getCookies();
}

Get a specific cookie

//This method is to get a specified cookie
public Cookie getCookieByName(String name) {
    return driver.manage().getCookieNamed(name);
}

Get the value of a specified cookie

//This method is to get the value of a specified cookie
public String getValueOfCookie(String name) {
    return driver.manage().getCookieNamed(name).getValue();
}

Create/Add a cookie

//This method adds or creates a cookie
public void addCookie(String name, String value, String domain, String path, Date expiry) {
    driver.manage().addCookie(new Cookie(name, value, domain, path, expiry));
}

Add multiple cookies

//This method adds multiple cookies for a domain
public void addMultipleCookiesToBrowser(Set<Cookie> cookies, String domain) {
    for (Cookie c : cookies) {
        if (c != null) {
           if (c.getDomain().contains(domain)){
              driver.manage().addCookie(
              new Cookie(name, value, domain, path, expiry));
           }
        }
    }
    driver.navigate().refresh();
}

Delete a specific cookie

//This method is used to delete a specific cookie
public void deleteCookieByName(String name) {
    driver.manage().deleteCookieNamed(name);
}

Remove/Delete all cookies

//This method is used to deletes all cookies
public void deleteAllCookies() {
    driver.manage().deleteAllCookies();
}

Leave a Reply

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