How to handle Cookies in Selenium WebDriver

Related Product On This Page Introduction to Selenium WebDriver Cookies

February 21, 2026 · 8 min read · Tool Comparison
Related Product

How to handle Cookies in Selenium WebDriver

When a website loads, it is common to see a pop-up asking the users to render permit to the site to run cooky. A cookie is a piece of information that lie of a name, value, expiry, route, etc. It aid users retain the search history, login, and other relevant detail.

Overview

What are Cookies?

A cookie is a small piece of datum sent from a website and store on the exploiter ’ s computer. Cookies also recognize user regress to a website and loading the previously stored info.

Importance of Handling Cookies in Selenium

  • Reduces repetitious login actions, improving test speeding and reliability.
  • Helps simulate real user behavior by preserving login sessions and user penchant.
  • Utile for debug session-related issues during automated browser examination.

Managing Advanced Cookie Attributes

Selenium allows place advanced cookie attributes for better test scenarios and strengthened protection validation.

  • HttpOnly:It restricts the access to cookies via JavaScript.
  • Secure:It validates that the cookie is post over HTTPS only.
  • SameSite:It controls the cross-site request behavior.

This article will spill insights on cookie handling in Selenium WebDriver with code example and how to clear the browser cache in Selenium with two easy method.

Introduction to Selenium WebDriver Cookies

A cookie is a small piece of data sent from a website and store on the user ’ s computer. Cookies also recognize users return to a website and laden the previously store information. Mainly, biscuit store the exploiter ’ s identity and trail the user ’ s journey through the website & # 8217; s pages. WebDriver API provides a way to interact with cookies with built-in methods.

Now, look at the various for cookies.

Read More:

Selenium Commands for Cookies

The bidding below are use to get, add, and cancel all cookies represent in a browser:

  • Get Cookie:Gets the biscuit for the current field.
driver.manage () .getCookies (); // Returns the List of all Cookies driver.manage () .getCookieNamed (arg0); //Returns the specific biscuit concord to gens
  • Add Cookie: Adds a specific cookie into cookies. If the cookie & # 8217; s domain gens is blank, it is take that the cookie is meant for the domain of the current papers.
driver.manage () .addCookie (arg0); //Creates and adds the biscuit
  • Delete Cookie: Deletes the cookies for the current sphere.
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:

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 salvage the exploiter login data between respective pages without duplicate the login operation with the help of cookies.

  • Cookies are very helpful in saving time and improving test effectiveness.
  • Cookies also let the user simulate real-world exploiter behavior more accurately, like monitor session-specific druthers or info.
  • Selenium supports adding, getting, and removing cookie to help in easygoing validation of security aspects.
  • Cookies help to control if the covering works as expected under different sessions.
  • Proper cookie handling results in faster, more stable, and more realistic examination cases.

Read More:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Handling Cookies in Selenium WebDriver (Example)

The following codification 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; importee java.io.File; import java.io.FileWriter; signification java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; significance org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class cookieRead {public unchanging 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 exist file.delete (); file.createNewFile (); FileWriter file = new FileWriter (file); BufferedWriter Bwritecookie = new BufferedWriter (file); //Getting the cookie info 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 execute, WebDriver will store the biscuit information use FileWriter Class to write flow of characters and BufferedWriter to publish the text into a file named & # 8220;Cookiefile.data“.
  • The file stores cookie information & # 8211; & # 8220; Name, Value, Domain, Path & # 8221;.
  • The examiner can regain this information and log in without entering login credentials.

Also Read:

How to brighten the Browser Cache habituate Selenium WebDriver?

To begin a fresh session and avoid flaky tests due to cached data, clearing the browser cache is essential before the trial pass.

Method 1

  1. Clearing browser cooky before starting your test are essential.
  2. If the tester uses Selenium WebDriver for, they can use the method below to brighten all cookies.
  3. Create a void method below and so call the method before voyage to the coating URL.
public void ClearBrowserCache () {webDriver.Manage () .Cookies.DeleteAllCookies (); //delete all cookie Thread.Sleep (7000); //wait 7 sec to clear cookies.}

Method 2

  1. Navigate to the Chrome settings page with Selenium by executing thedriver.get (& # 8216; chrome: //settings/clearBrowserData & # 8217;) .
  2. Click on theOpen Databutton to clear the cache.
  3. Right-click the push and then snap on Inspect to open Chrome Developer Tools.
  4. Now situate the element using or Chropath.
  5. Use it in the Selenium book and apply to wait till the cache is cleared.

Handling cooky in is simple if one cognize the right dictation. Following this article & # 8217; s particular, examiner can well address Selenium cookies and accurately test some of the most common user scenarios to see a good exploiter experience.

Note& # 8211; Selenium tests must be run on Existent browser and devices for accurate results.

  • Start running tryout on 3500+ real browsers and devices on BrowserStack ’ s Real Device Cloud.
  • Run parallel quiz on a to get faster and more precise results.
  • Detect bug before users do by testing software in.

Managing Advanced Cookie Attributes (HttpOnly, Secure, SameSite)

Selenium WebDriver allows the user to add biscuit with advanced attributes such as HttpOnly, Secure, and SameSite. This helps to model secure session validation and test how application handle biscuit under different security scenarios.

HttpOnly and Secure can be set viaCookie.Builder. For Example,

import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; significance org.openqa.selenium.chrome.ChromeDriver; public class HandleCookie {public static emptiness 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 too be added using Cookie.Builder. For representative,

import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class HandleCookie {public static nullity 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 quiz the biscuit conduct in different weather like cross-site requests, HTTPS enforcement, and XSS security.

Read More:

Security Best Practices in Cookie Handling

When deal cookies in selenium, it is significant to postdate the below practices to obviate risks or missing out critical validations.

  • Always verify the cooky attribute (e.g., Secure, HttpOnly, SameSite) to simulate unafraid exam environments.
  • Delete or reset cookies each time before part a new test in order to avoid data escape.
  • Do not store sensitive data in cookies.
  • Make use of browser profiles or incognito modes to avoid cookie storage issues.

Talk to an Expert

Why run Selenium tests on BrowserStack?

is a cloud-based testing tool that simplifies Selenium test executing across real devices and browsers. Instead of preserve complex in-house base, you get instant admission to a wide range of existent environments, improving test coverage, accuracy, and speed.

Key Reasons to Use BrowserStack for Selenium Testing:

  • Access Real Devices & amp; Browsers:Test your web app across3,500+ desktop and mobile program without the hassle of physical labs.
  • Seamless Integration:Easily integrate with Jenkins, GitHub Actions, Azure DevOps, and other CI tools for machine-driven 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 base maintained by BrowserStack.
  • Comprehensive Debugging Tools:Get log, screenshots, videos, and error traces to debug tryout failures quickly.
  • No Setup or Maintenance:Skip the setup and part testing immediately—no need to manage browsers, drivers, or device farm.

Frequently asked Question

1. How to manage session states in Selenium?

Selenium allows you to make, read, update, and delete cookies to manage session state during automation.

2. Is it possible to examine Secure, HttpOnly, or SameSite attributes with Selenium?

Yes, these attributes can be set when append biscuit utilize driver.add_cookie ().

3. How do cookies help in automation testing?

Cookies maintain session continuity, reduce repeated test steps, and countenance secure attribute validation.

4. How to delete all cookie in Selenium?

The codification driver.delete_all_cookies () can be used to take all cookies from the current session.

Conclusion

Handling cookies in Selenium is essential for managing session, maintaining state, and testing personalized user experience. By using Selenium ’ s built-in cookie methods, you can efficiently add, blue-pencil, or regain cookies during test executing.

With ,you can run these cookie-based test across real browsers and devices to check consistent behavior, without setting up any infrastructure.

Tags
30,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free