How To Handle Cookies in Selenium WebDriver

Posted by Shalini Baskaran | July 28, 2021
Automation • Selenium Java •

236242 Views | 10 Min Read

Handle Cookies in Selenium

Most of us use online platforms for doing things like online shopping, bill payments, ticket booking, and more. These online platforms (or websites) use cookies to identify whenever there is a new visit. On a lighter note, these are not cookies that you would normally see on your dessert menu 🙂 These are computer cookies (or HTTP cookies or web cookies).

In simple terms, a cookie is a packet of data received by your machine and sent back to the server without being altered or changed. For example, when you visit any website, cookies are sent to your machine by the website. Since these cookies contain information, it helps the website keep track of your visits or activity (without indulging in your privacy zone).

gif

Source

Website owners (e.g., online shopping portals) use cookies to keep a tab on your shopping cart while browsing the site. Without the presence of cookies, your shopping cart might become empty (or the item count would reset to zero) each time you open up a new link on the site.

Selenium cookies can be extensively used for test automation projects for performing cookie-related operations during the process of Selenium automation testing. To realize this requirement, Selenium WebDriver API provides built-in methods for interacting with the cookies.

By the end of this blog, you would be better positioned to work with Selenium cookies API. We also cover common operations like how to get cookies in Selenium WebDriver, clearing session cookies using Selenium, and more.

So, let’s get started biting the cookies 🙂

Introduction to Cookies

Cookies are usually used to recognize the identity of a user on a website. In simple terms, a cookie is a portion of data that has been sent from a web application and stored in a browser. Whenever a user browses a website, the information about the user and their favorites is stored as a cookie in the form of key-value pairs.

When the user visits the website again, the information which was stored would be used for identification.

Below is an example of the LambdaTest website that uses cookies for recognizing the user. In the below screenshot, you can see a small popup that shows the usage of cookies.

cross browser testing

  • Name – This field contains the cookie’s name.
  • Value – This field contains the cookie’s value.
  • Domain – This field contains the hosts that are allowed to receive the cookie.
  • Path – This field contains the URL required in the requested URL to send the Cookie header.
  • Expires / Max-Age – This field contains the expiration date or the maximum age of the cookie.
  • Size – This field contains the size of the cookie.
  • HttpOnly – This field indicates whether the cookie has to be used only over HTTP or not.
  • Secure – This field indicates that the cookie can only be sent to the server over a secure HTTPS connection (set as true).
  • SameSite – This field contains the values (strict or lax) if the cookie is using the experimental SameSite attribute.
  • Priority – This field Contains low, medium (default), or high values if the depreciated cookie Priority attribute is enabled.

website cookies

Here are the major functions of website cookies:

  1. Tracking the browsing activity of the user
  2. Remembering the login details of the user
  3. Tracking the visitor count in a website further helps the website owners identify their unique visitors every day.

Why handle cookies in Selenium Automation WebDriver

This section unearths the major reasons for using Selenium cookies API in a test automation script. The important aspect of storing cookies and handling them in our automation script is to reduce the time taken for implementation and execution.

Take the case where we have multiple test cases, and each of them has a prerequisite to log into the website. In such scenarios, we can store the cookies, which can then be used for login purposes. This, in turn, helps in reducing the execution time.

Introduction to Selenium Cookies API

Selenium WebDriver provides multiple commands for handling the cookies in a website. These Selenium cookies APIs provide you the required mechanism for interacting and querying the cookies. In Selenium Java, these methods are a part of the org.openqa.selenium.Cookie package.

Here are the various methods to handle cookies in Selenium that can be accessed using driver.manage() method:

Method

Purpose

getCookies()

It returns the list of all the cookies

getCookieNamed(“Name of Cookie”)

It returns the cookie that matches the name specified as the argument

addCookie(“Cookie”) 

It creates and adds a new cookie

deleteCookie(“Cookie”)

It deletes a particular cookie

deleteCookieName(“Name of Cookie”)

It deletes the cookie that matches the name specified as the argument

deleteAllCookies

It deletes all the cookies

Selenium Cookies API in Action

Now that we have covered the basic aspects of handling cookies in Selenium WebDriver let’s get our hands dirty with some implementation. For demonstrating handling cookies in Selenium, we first use the corresponding Selenium APIs on a local Selenium Grid. If you want to quickly brush up on your Selenium skills, check out our detailed Selenium WebDriver tutorial.

Let us use the LambdaTest home page in our script to understand the commands used for handling cookies using Selenium WebDriver.

1. How to Get Cookies in Selenium WebDriver

As mentioned earlier, if you want to get all the stored cookies, you can use the below Selenium WebDriver command.

This will retrieve details of all the stored cookies. Below is a simple script to get cookies in Selenium WebDriver:

The cookie information can be stored in a file that can be used for logging into the website without the credentials.

To get information about a specific cookie, use the below command:

Below is a simple script for getting information about a specific cookie:

The implementation is self-explanatory; hence, we are not doing a code walkthrough of the same.

2. How to Add a new Cookie in Selenium WebDriver

To add a new cookie, you can use the below command

Before adding a cookie, we have to create it and add the values. Post that, we should pass the name of the newly created cookie.

Here is a simple script that demonstrates Selenium cookies API for adding a new cookie.

Once you run the test script, you would be able to see the newly added cookie in the output console:

cookies

3. How to Delete a Cookie in Selenium WebDriver

With the help of the Selenium WebDriver commands, you can delete a specific cookie or delete all the cookies.

This command is used for deleting a specific cookie:

This command is used for deleting a specific cookie that is matched using its name:

This command is used for deleting all the cookies:

Here is the same script that demonstrates how to delete a specific cookie:

The below script demonstrates how to use Selenium cookies API for deleting all the cookies:

How to use Selenium Cookies API on Cloud Selenium Grid

Rather than running Selenium tests on a local Selenium Grid, it is recommended to execute the same on a cloud-based Selenium Grid like LambdaTest. There are numerous benefits of website testing on cloud since it helps achieve much-needed scalability, reliability, and performance.

LambdaTest provides an online cloud platform to run all your Selenium tests with ease. In addition, it is easy to port the code that uses the local Selenium Grid to LambdaTest’s cloud-based Selenium Grid. Thus, you can make the most out of parallel testing in Selenium by moving the Selenium test automation to a cloud-based Grid.

cross browser testing

Once you have created an account on LambdaTest, note the username & access key available in the profile section of LambdaTest. The combination of username & access key is used for accessing the Remote Selenium Grid of LambdaTest. The capabilities are generated using the LambdaTest capabilities generator.

Shown below is the demonstration of Selenium cookies API with the execution being performed on the LambdaTest Selenium Grid:

As seen above, there are no logic changes, and most of the implementation remains unchanged. However, instead of the local Selenium WebDriver, the Remote WebDriver is used for accessing the cloud-based Selenium Grid.

Since we have four tests in the test suite, we leverage parallel testing in TestNG Selenium to realize parallelism at the Thread level. Shown below is the testng.xml file that runs tests under the @Test annotation in parallel. In addition, you can check out more TestNG Learning Hub on LambdaTest to gain insights into the TestNG framework.

Below is the test execution status of our tests in Eclipse:

selenium webdriver

To run this test in the LambdaTest platform, right-click on the testng.xml that you have created in the IDE. Click Run As –> TestNG Suite. With this, the test would be triggered on the LambdaTest platform.

Shown below is the console output, which indicates that the test execution was successful:

webdriver

Hop on to the Automation Dashboard on LambdaTest for checking the status of the test execution:

Automation Dashboard on LambdaTest

Automation Dashboard

With this we have demonstrated the major Selenium cookies APIs that can be used for performing operations on the cookies.

It’s a Wrap

ezgif.com-gif-maker

To summarize, we deep-dived into the various aspects of cookies primarily used for website owners to track the user’s visits or activity. Selenium provides methods (or APIs) using which you can perform various actions on the cookies. We demonstrated how to get cookies in Selenium, how to delete all the cookies in Selenium, how to delete a certain cookie, and more.

Rather than performing Selenium automation testing on a local Selenium Grid, it is recommended to expedite the test execution using a cloud-based Selenium grid like LambdaTest. It lets you run Selenium tests at scale on 2,000+ browsers and operating systems.

youtube channel

I hope you find this article very useful and informative. I would love to hear how you use Selenium cookies API for large-scale websites (or web apps). Please feel free to share this blog with your friends and colleagues.

Happy Testing…!

Frequently Asked Questions

What is a cookie in Selenium?

A cookie is a small file stored on your computer when you access certain websites. Cookies are used to collect and store information about how you interact with our website and allow us to remember you even if you return to the site at a later time.

Can Selenium manipulate cookies?

Selenium provides functions to capture, manipulate and set cookies. It also provides the function to check whether a given cookie exists or not. You can interact and query Selenium cookies using the following:

  • .getCookies() – returns the list of all cookies
  • .getCookieNamed(“cookie name”) – returns cookie based on its name
  • .addCookie(“cookie”) – creates and adds a cookie
  • .deleteCookie(“cookie”) – deletes a cookie
  • .deleteCookieName(“cookie name”) – deletes cookie based on its name
  • .deleteAllCookies – delete all the cookies
LtAutomate Your Website Tests Now, Claim 100 Minutes Free
X

Written by

Related Articles

Leave a Reply

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