Selenium Cookies | All Details with Examples!

Selenium Cookies are important in test automation projects to do the cookie-related operations during our test execution. In this post, we will learn all cookie operations in selenium such as clear session cookies, add cookie, how to get cookie, etc.

First, we will learn what a cookie is and all details of Selenium Cookies API. Selenium webdriver can handle cookies with its built-in methods. Let’s get started!

What is a Cookie?

Cookies comprise information about us and our preferences. A website places this information into our computer so that we can remember it in the future. Simply, a website can recognize you with cookies and look up your preferences.

For instance, when we select the language preference of a website, then the browser will save that information into a little document (cookie) on our PC. Next time we visit that website, a browser will read that cookie then remember our previous language preference, and change the website’s language automatically.

As remembering your language preference, cookies can contain and remember any kind of information such as your visit time of a website, products that you added to your shopping basket, all the links that you clicked on a website, etc.

The cookie mechanism allows that the server (webpage) holds its own information about a user on the user’s PC. We can view the details of any cookie and also can delete them.

Web users have to agree to let cookies be saved for them into their PC so websites can remember their cookies for better service. Also, in order to reduce cookie size, a unique ID is stored into that cookie and the rest of the personal data is stored in the website’s servers. These kinds of cookies are called third-party cookies.

By the way, one of the most important cookies is the authentication cookies that provide login and account status to the web servers. The security of these cookies generally depends on the security of the related website and user’s web browser, also the encryption of the cookie’s data.

For more information about cookies please go to the below links:
https://www.youtube.com/watch?v=I01XMRo2ESg
https://en.wikipedia.org/wiki/HTTP_cookie

Selenium Cookies API

In selenium webdriver, we can query and interact with cookies with the below built-in methods.

Interact and Query with Selenium Cookies

driver.manage

  • .getCookies()returns the list of all cookies
  • .getCookieNamed(“cookie name”)returns a specific cookie according to its name
  • .addCookie(“cookie”)creates and adds a cookie
  • .deleteCookie(“cookie”)deletes specific cookie
  • .deleteCookieName(“cookie name”)deletes specific cookie according to its name
  • .deleteAllCookiesdelete all the cookies

Cookie.Builder

We can create cookies with Cookie.Builder is an easy and convenient way instead of using a constructor to create a new cookie. You can build a new cookie by typing “new Cookie.Builder”. Its constructor gets some parameters such as name, value, path, domain, expiration date, is secure, etc. and at the last, we can finish the declaration with .build() to create a cookie with the builder. Name and value are mandatory fields for creating a cookie with Cookie.Builder. I am sharing two examples for Cookie.Builder.

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class CookieBuilderExample {
    Date today    = new Date();
    Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

    Cookie newCookie = new Cookie.Builder("myCookie","my value") //Name & value pair of the cookie (mandatory fields)
        .domain("www.swtestacademy.com") //Domain of the cookie
        .path("/") //Path of the cookie
        .expiresOn(tomorrow) //Expiration date
        .isSecure(true) //Is it secure or not?
        .build(); //Finally build it with .build() call

    @Test
    public void promptCookie (){
        System.out.println("My new Cookie: " + newCookie);
    }
}

Selenium Cookies Example

In the below example, you can find almost all cookie operations in Selenium. Cookie operations in these examples are listed below:

  • Get all the Cookies and print the total number of Cookies.
  • Copy a cookie
  • Create a new cookie
  • Add a cookie
  • Delete a cookie
  • Clear session cookies
  • Print all cookies
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class CookieExample {
    private        WebDriver driver;
    private static String    url = "https://www.swtestacademy.com";

    @BeforeAll
    public void setupTest() {
        driver = new ChromeDriver();
        driver.navigate().to(url);
        driver.manage().window().maximize();
    }

    @Test
    public void cookieTest() {
        //Get all the Cookies and print the total number of Cookies.
        printCookieNumber("First Time");

        //Get the cookie which name is “_gat” with getName() method and print its value.
        Cookie cookie = driver.manage().getCookieNamed("_gat");
        System.out.println("cookie: " + cookie +"\n");
        System.out.println("cookie value: " + cookie.getValue() + "\n");

        //Copy above cookie as copiedCookie and print it and total cookie number.
        Cookie copiedCookie = driver.manage().getCookieNamed("_gat");
        System.out.println("Copied cookie: " + copiedCookie +"\n");

        //Create new Cookie as “myCookie” with Cookie.Builder and print it.
        Cookie myCookie = new Cookie.Builder("myCookie", "Created by manually cookie.")
            .domain(cookie.getDomain())
            .path( cookie.getPath())
            .expiresOn(cookie.getExpiry())
            .isSecure(cookie.isSecure()).build();
        System.out.println("Built cookie: " + myCookie +"\n");

        //Delete the cookie
        driver.manage().deleteCookie(cookie);

        //print cookie number after deleting cookie.
        printCookieNumber("After Deleting the _gat Cookie");

        //Add new cookie by using “myCookie”
        driver.manage().addCookie(myCookie);

        //Add new cookie by using “copiedCookie”
        driver.manage().addCookie(copiedCookie);

        //Print cookie number after adding two cookies.
        printCookieNumber("After Adding Two Cookies");

        //Delete builtCookie by using .deleteCookieName
        driver.manage().deleteCookieNamed("myCookie");

        //Delete copiedCookie by using deleteCookieNamed
        driver.manage().deleteCookieNamed("_gat");

        //Print cookie number after deleting two cookies.
        printCookieNumber("After Deleting Two Cookies");

        //Delete all cookies.
        driver.manage().deleteAllCookies();

        //Print cookie number after deleting all the cookies.
        printCookieNumber("After Deleting All Cookies");

    }

    private void printCookieNumber (String message) {
        //Get all cookies of the site
        Set<Cookie> cookies = driver.manage().getCookies();
        List<Cookie> cookieList = new ArrayList<>(cookies); //Set to List Conversion
        System.out.println("Total number of Cookies ~~~" + message + "~~~ : " + cookieList.size() + "\n");

        //Print all cookie names and values
        for (int i=0; i<cookieList.size(); i++) {
            System.out.println("Cookie " + i + " name: " + cookieList.get(i).getName() +
                " value: " + cookieList.get(i).getValue());
        }
        System.out.println("---------------------------------------------------------\n");
    }

    @AfterAll
    public void quitDriver() {
        driver.quit();
    }
}

Console Output

Total number of Cookies ~~~First Time~~~ : 4

Cookie 0 name: _gat value: 1
Cookie 1 name: _ga value: GA1.2.1070980939.1618124408
Cookie 2 name: __gads value: ID=46c51759467a62bb-2263be3c7ea7009e:T=1618124412:RT=1618124412:S=ALNI_MZeOeWo9uxNUlrtubqYvpQetx4I6w
Cookie 3 name: _gid value: GA1.2.81586050.1618124408
---------------------------------------------------------

cookie: _gat=1; expires=Sun, 11 Apr 2021 11:01:07 GST; path=/; domain=.swtestacademy.com

cookie value: 1

Copied cookie: _gat=1; expires=Sun, 11 Apr 2021 11:01:07 GST; path=/; domain=.swtestacademy.com

Built cookie: myCookie=Created by manually cookie.; expires=Sun, 11 Apr 2021 11:01:07 GST; path=/; domain=.swtestacademy.com

Total number of Cookies ~~~After Deleting the _gat Cookie~~~ : 3

Cookie 0 name: _ga value: GA1.2.1070980939.1618124408
Cookie 1 name: __gads value: ID=46c51759467a62bb-2263be3c7ea7009e:T=1618124412:RT=1618124412:S=ALNI_MZeOeWo9uxNUlrtubqYvpQetx4I6w
Cookie 2 name: _gid value: GA1.2.81586050.1618124408
---------------------------------------------------------

Total number of Cookies ~~~After Adding Two Cookies~~~ : 5

Cookie 0 name: _gat value: 1
Cookie 1 name: myCookie value: Created by manually cookie.
Cookie 2 name: _ga value: GA1.2.1070980939.1618124408
Cookie 3 name: __gads value: ID=46c51759467a62bb-2263be3c7ea7009e:T=1618124412:RT=1618124412:S=ALNI_MZeOeWo9uxNUlrtubqYvpQetx4I6w
Cookie 4 name: _gid value: GA1.2.81586050.1618124408
---------------------------------------------------------

Total number of Cookies ~~~After Deleting Two Cookies~~~ : 3

Cookie 0 name: _ga value: GA1.2.1070980939.1618124408
Cookie 1 name: __gads value: ID=46c51759467a62bb-2263be3c7ea7009e:T=1618124412:RT=1618124412:S=ALNI_MZeOeWo9uxNUlrtubqYvpQetx4I6w
Cookie 2 name: _gid value: GA1.2.81586050.1618124408
---------------------------------------------------------

Total number of Cookies ~~~After Deleting All Cookies~~~ : 0

---------------------------------------------------------

Github Project

https://github.com/swtestacademy/selenium-examples/tree/main/src/test/java/cookies

Thanks.
Onur

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.