When a website loads, it is common to see a pop-up asking the users to provide permission to the site to run cookies. A cookie is a piece of information that consists of a name, value, expiry, path, etc. It helps users retain the search history, login, and other relevant details.
Overview
What are Cookies?
A cookie is a small piece of data sent from a website and stored on the user’s computer. Cookies also recognize users returning to a website and loading the previously stored information.
Importance of Handling Cookies in Selenium
- Reduces repetitive login actions, improving test speed and reliability.
- Helps simulate real user behavior by preserving login sessions and user preferences.
- Useful for debugging session-related issues during automated browser testing.
Managing Advanced Cookie Attributes
Selenium allows setting advanced cookie attributes for better test scenarios and strengthened security validations.
- HttpOnly: It restricts the access to cookies via JavaScript.
- Secure: It validates that the cookie is sent over HTTPS only.
- SameSite: It controls the cross-site request behavior.
This article will shed insights on cookies handling in Selenium WebDriver with code examples and how to clear the browser cache in Selenium with two easy methods.
Introduction to Selenium WebDriver Cookies
A cookie is a small piece of data sent from a website and stored on the user’s computer. Cookies also recognize users returning to a website and loading the previously stored information. Mainly, cookies store the user’s identity and track the user’s journey through the website’s pages. WebDriver API provides a way to interact with cookies with built-in methods.
Now, look at the various Selenium commands for cookies.
Selenium Commands for Cookies
The commands below are used to get, add, and delete all cookies present in a browser:
- Get Cookie: Gets the cookies for the current domain.
driver.manage().getCookies(); // Returns the List of all Cookies driver.manage().getCookieNamed(arg0); //Returns the specific cookie according to name
- Add Cookie: Adds a specific cookie into cookies. If the cookie’s domain name is blank, it is assumed that the cookie is meant for the domain of the current document.
driver.manage().addCookie(arg0); //Creates and adds the cookie
- Delete Cookie: Deletes the cookies for the current domain.
driver.manage().deleteCookie(arg0); // Deletes the specific cookie driver.manage().deleteCookieNamed(arg0); // Deletes the specific cookie according to the Name driver.manage().deleteAllCookies(); // Deletes all the cookies
Read More: Cookie Testing in Software Testing
Importance of Cookie Handling in Selenium Automation WebDriver
Cookie management is a very important step as a part of Selenium automation. Testers are able to save the user login data between several pages without repeating the login process with the help of cookies.
- Cookies are very helpful in saving time and improving test effectiveness.
- Cookies also let the user simulate real-world user behavior more accurately, like monitoring session-specific preferences or information.
- Selenium supports adding, getting, and removing cookies to assist in easier validation of security aspects.
- Cookies help to verify if the application works as expected under different sessions.
- Proper cookie handling results in faster, more stable, and more realistic test cases.
Read More: Selenium WebElement Commands
Handling Cookies in Selenium WebDriver (Example)
The following code snippet demonstrates how to store cookies in a file system and retrieve the necessary information with the help of Selenium WebDriver.
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class cookieRead{ public static void main(String[] args){ WebDriver driver; System.setProperty("webdriver.chrome.driver","Chrome_driver_path"); driver=new ChromeDriver(); driver.get("https://www.facebook.com"); //Enter Email id and Password if you are already Registered user driver.findElement(By.name("username")).sendKeys("your_username"); driver.findElement(By.name("password")).sendKeys("your_password"); driver.findElement(By.name("submit")).click(); // Create a file to store Login Information File file = new File("Cookiefile.data"); try{ // Delete old file if already exists file.delete(); file.createNewFile(); FileWriter file = new FileWriter(file); BufferedWriter Bwritecookie = new BufferedWriter(file); //Getting the cookie information for(Cookie ck : driver.manage().getCookies()) { Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure())); Bwritecookie.newLine(); } Bwritecookie.close(); file.close(); } catch(Exception ex) { ex.printStackTrace(); } } }
- When the code is executed, WebDriver will store the cookie information using FileWriter Class to write streams of characters and BufferedWriter to write the text into a file named “Cookiefile.data“.
- The file stores cookie information – “Name, Value, Domain, Path”.
- The tester can retrieve this information and log in without entering login credentials.
Also Read: Login Automation using Selenium Webdriver
How to clear the Browser Cache using Selenium WebDriver?
To start a fresh session and avoid flaky tests due to cached data, clearing the browser cache is essential before the test runs.
Method 1
- Clearing browser cookies before starting your test are essential.
- If the tester uses Selenium WebDriver for test automation, they can use the method below to clear all cookies.
- Create a void method below and then call the method before navigating to the application URL.
public void ClearBrowserCache() { webDriver.Manage().Cookies.DeleteAllCookies(); //delete all cookies Thread.Sleep(7000); //wait 7 seconds to clear cookies. }
Method 2
- Navigate to the Chrome settings page with Selenium by executing the driver.get(‘chrome://settings/clearBrowserData’) .
- Click on the Clear Data button to clear the cache.
- Right-click the button and then click on Inspect to open Chrome Developer Tools.
- Now locate the element using XPath or Chropath.
- Use it in the Selenium script and apply wait commands to wait till the cache is cleared.
Handling cookies in Selenium is simple if one knows the right commands. Following this article’s details, testers can easily handle Selenium cookies and accurately test some of the most common user scenarios to ensure a good user experience.
Note – Selenium tests must be run on Real browsers and devices for accurate results.
- Start running tests on 3500+ real browsers and devices on BrowserStack’s Real Device Cloud.
- Run parallel tests on a Cloud Selenium Grid to get faster and more accurate results.
- Detect bugs before users do by testing software in real user conditions.
Managing Advanced Cookie Attributes (HttpOnly, Secure, SameSite)
Selenium WebDriver allows the user to add cookies with advanced attributes such as HttpOnly, Secure, and SameSite. This helps to simulate secure session validations and test how applications handle cookies under different security scenarios.
HttpOnly and Secure can be set via Cookie.Builder. For Example,
import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class HandleCookie { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", System.getProperty(“***Path to driver file***"); WebDriver driver = new ChromeDriver(); driver.get("https://bstackdemo.com"); Cookie secureCookie = new Cookie.Builder("session_id", "abc123secure") .domain("bstackdemo.com") .path("/") .isHttpOnly(true) .isSecure(true) .build(); driver.manage().addCookie(secureCookie); driver.navigate().refresh(); // To Check Cookies for (Cookie cookie : driver.manage().getCookies()) { System.out.println(cookie.getName() + " = " + cookie.getValue()); } driver.quit(); } }
Samesite can also be added using Cookie.Builder. For example,
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class HandleCookie { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", System.getProperty(“***Path to driver file***"); WebDriver driver = new ChromeDriver(); driver.get("https://bstackdemo.com"); Cookie sameSiteCookie = new Cookie.Builder("test_samesite", "value123") .domain("bstackdemo.com") .path("/") .isSecure(true) .sameSite("Strict") .build(); driver.manage().addCookie(sameSiteCookie); driver.navigate().refresh(); // To Verify Cookies for (Cookie cookie : driver.manage().getCookies()) { System.out.println(cookie.getName() + " = " + cookie.getValue()); } driver.quit(); } }
The above attributes can be used to test the cookie behavior in different conditions like cross-site requests, HTTPS enforcement, and XSS protection.
Read More: What is ChromeDriver?
Security Best Practices in Cookie Handling
When managing cookies in selenium, it is important to follow the below practices to avoid risks or missing out critical validations.
- Always verify the cookie attributes (e.g., Secure, HttpOnly, SameSite) to simulate secure test environments.
- Delete or reset cookies each time before starting a new test in order to avoid data leakage.
- Do not store sensitive data in cookies.
- Make use of browser profiles or incognito modes to avoid cookie storage issues.
Why run Selenium tests on BrowserStack?
BrowserStack Automate is a cloud-based testing tool that simplifies Selenium test execution across real devices and browsers. Instead of maintaining complex in-house infrastructure, you get instant access to a wide range of real environments, improving test coverage, accuracy, and speed.
Key Reasons to Use BrowserStack for Selenium Testing:
- Access Real Devices & Browsers: Test your web app across 3,500+ desktop and mobile platforms without the hassle of physical labs.
- Seamless CI/CD Integration: Easily integrate with Jenkins, GitHub Actions, Azure DevOps, and other CI tools for automated test pipelines.
- Faster Test Execution with Parallel Runs: Run multiple Selenium tests simultaneously to speed up release cycles.
- Reliable, Scalable Infrastructure: Eliminate flakiness with secure, globally available test infrastructure maintained by BrowserStack.
- Comprehensive Debugging Tools: Get logs, screenshots, videos, and error traces to debug test failures quickly.
- No Setup or Maintenance: Skip the setup and start testing immediately—no need to manage browsers, drivers, or device farms.
Frequently asked Question
1. How to manage session states in Selenium?
Selenium allows you to create, read, update, and delete cookies to manage session states during automation.
2. Is it possible to test Secure, HttpOnly, or SameSite attributes with Selenium?
Yes, these attributes can be set when adding cookies using driver.add_cookie().
3. How do cookies help in automation testing?
Cookies maintain session continuity, reduce repeated test steps, and allow secure attribute validation.
4. How to delete all cookies in Selenium?
The code driver.delete_all_cookies() can be used to remove all cookies from the current session.
Conclusion
Handling cookies in Selenium is essential for managing sessions, maintaining state, and testing personalized user experiences. By using Selenium’s built-in cookie methods, you can efficiently add, delete, or retrieve cookies during test execution.
With BrowserStack Automate, you can run these cookie-based tests across real browsers and devices to ensure consistent behavior, without setting up any infrastructure.