How to Handle Cookies in Selenium

 

Cookies are used to track user in website. 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. It is used to store the user’s identity and track the user’s journey through the website’s pages.

In Selenium WebDriver (Java), cookies represent small pieces of data stored in the browser by the website. These can include session IDs, user preferences, authentication tokens, etc.


👉 Selenium allows you to:

  • Get all cookies

  • Add a cookie

  • Delete a cookie

  • Delete all cookies


👉 Cookies are especially useful for:

  • Maintaining sessions between tests

  • Simulating logged-in users without going through login pages

  • Testing scenarios involving cookies


👉 Cookie Methods in Selenium Java

Selenium provides cookie handling through the WebDriver.Options interface via driver.manage().getCookies() and related methods.


MethodDescription
driver.manage().getCookies()Returns a set of all cookies
driver.manage().getCookieNamed("name")Returns a specific cookie by name
driver.manage().addCookie(Cookie cookie)Adds a new cookie
driver.manage().deleteCookie(cookie)Deletes a specific cookie
driver.manage().deleteCookieNamed("name")Deletes a cookie by name
driver.manage().deleteAllCookies()Deletes all cookies


How to add a cookie in Selenium

Below is the sample code to add a cookie by Selenium java:


package com.cookies;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AddCookie {
    
    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        
        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        
        driver.get("https://www.google.com");
        
        Cookie cookie = new Cookie("newCookie","goformule");
        driver.manage().addCookie(cookie);
        
        Thread.sleep(2000);
        driver.quit();
        
    }
}


How to get a cookie in Selenium:

Below is the sample code to get a cookie by Selenium java:



package com.cookies;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GetCookie {

    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        driver.get("https://www.google.com");

        Cookie cookie = new Cookie("newCookie", "goformule");
        driver.manage().addCookie(cookie);
        
        Cookie cookieName = driver.manage().getCookieNamed("newCookie");
        System.out.println("Cookie Name: "+cookieName.getValue());
        
        Thread.sleep(2000);
        driver.quit();
    }

}

Output:

Cookie Name: tutorials123



How to get all cookies in Selenium:

Below is the sample code to get all cookies by Selenium java:

package com.cookies;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GetAllCookies {
    
    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        driver.get("https://www.google.com");
        
        Set<Cookie> set = driver.manage().getCookies();
        
        Iterator<Cookie> it = set.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
        
        Thread.sleep(2000);
        driver.quit();
    }

}

How to delete a cookie in Selenium

Below is the sample code to delete a cookie by Selenium java:


package com.cookies;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DeleteCookie {
    
    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        driver.get("https://www.google.com");
        
        Cookie cookie = new Cookie("newCookie","goformule");
        driver.manage().addCookie(cookie);

        driver.manage().deleteCookie(cookie);
        System.out.println("Cookies Deleted");

        Thread.sleep(2000);
        driver.quit();
    }
    



}

Output:

Cookies Deleted


How to delete a cookie by name in Selenium

Below is the sample code to delete a cookie by name by Selenium java:



package com.cookies;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DeleteCookieByName {
    
    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        driver.get("https://www.google.com");
        
        driver.manage().deleteCookieNamed("goformule");
        System.out.println("Cookies Deleted");

        Thread.sleep(2000);
        driver.quit();
    }



}

Output:

Cookies Deleted


How to delete all cookies in Selenium

Below is the sample code to delete all cookies by Selenium java:


package com.cookies;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DeleteAllCookies {

    static String projectLocation = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver", projectLocation + "/driver/chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        // maximize window
        driver.manage().window().maximize();

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

        // dynamic wait
        driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        driver.get("https://www.google.com");

        driver.manage().deleteAllCookies();
        System.out.println("Cookies Deleted");

        Thread.sleep(2000);
        driver.quit();
    }
}

Output:

Cookies Deleted

WebDriver Element Locator Firefox Add On

 

In Selenium with Java, WebDriver Element Locators are used to find and interact with elements on a web page. For Firefox, a helpful tool to identify and inspect these elements is the Firefox Add-on called "Firebug" which is older version, or "Web Developer Tools" which is modern Firefox version. Here’s how it all fits together:


Common Element Locators in Selenium Java

  • id
  • name
  • className
  • tagName
  • linkText
  • partialLinkText
  • cssSelector
  • xpath

Modern Method: Firefox DevTools (Built-in)

No need for an external add-on anymore:

  • Right-click on any element > Inspect

  • The HTML structure opens at the bottom.

  • Right-click the element again > Copy > choose CSS Selector or XPath


How to Use in Selenium Java:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirefoxLocatorExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");

        WebDriver driver = new FirefoxDriver();
        driver.get("https://example.com");

        // Locate by ID
        WebElement elementById = driver.findElement(By.id("username"));

        // Locate by Name
        WebElement elementByName = driver.findElement(By.name("password"));

        // Locate by XPath (copied from Firefox DevTools)
        WebElement elementByXpath = driver.findElement(By.xpath("//input[@id='login']"));

        // Locate by CSS Selector
        WebElement elementByCss = driver.findElement(By.cssSelector("input[type='submit']"));

        elementByCss.click();
        
        driver.quit();
    }
}


How to use Robot Class in Selenium

  

The Robot Class in Java belongs to the java.awt package. It is used in Selenium to handle keyboard and mouse events that cannot be handled using the WebDriver or Actions class such as file upload windows, OS-level popups, or simulating keyboard shortcuts like Ctrl+S, Alt+Tab, etc.


Use Cases of Robot Class

  • Handling file upload dialogs (OS windows)

  • Simulating keyboard shortcuts (example: Ctrl+C, Enter)

  • Performing mouse movements or clicks outside the browser

  • Dealing with download popups, print popups, etc.


Common Robot Class Methods

MethodDescription
keyPress(int keycode)Presses a key
keyRelease(int keycode)Releases a key
mouseMove(int x, int y)Moves mouse pointer to (x, y) screen coordinates
mousePress(int buttons)Presses mouse buttons
mouseRelease(int buttons)Releases mouse buttons
delay(int ms)Delays execution for specified milliseconds


Uses KeyEvent.VK_* constants for keys, e.g., KeyEvent.VK_ENTER, KeyEvent.VK_CONTROL.


File upload example: Selenium Script Using Robot Class 

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RobotClassFileUploadExample {
    public static void main(String[] args) throws AWTException, InterruptedException {
        // Set path to chromedriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize driver
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        // Open sample file upload site
        driver.get("https://www.filemail.com/share/upload-file");

        // Click on "Add Files" button to open OS file upload dialog
        driver.findElement(By.xpath("//button[text()='Add Files']")).click();

        // Wait for file upload window to appear
        Thread.sleep(2000);

        // Set the file path to clipboard
        StringSelection filePath = new StringSelection("C:\\Users\\YourUser\\Documents\\sample.txt");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePath, null);

        // Use Robot to press CTRL+V and Enter
        Robot robot = new Robot();
        robot.delay(1000);

        // Press CTRL + V
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

        robot.delay(500);

        // Press Enter
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

        // Done!
        Thread.sleep(3000);
        driver.quit();
    }
}


Suppose we are uploading a file to a form, and we need to handle the OS file chooser window:



Explanation:

  • StringSelection + Toolkit.getDefaultToolkit().getSystemClipboard() → Puts file path into clipboard.

  • Robot simulates Ctrl+V and Enter to paste the path and upload the file.


Important points:

  • Robot class interacts outside of browser context, so it can handle system-level dialogs.

  • Always add Thread.sleep() or robot.delay() to ensure the timing is synced properly with the UI events.

Right Click and Double Click in Selenium

 

In Selenium with Java, you can perform Right Click (Context Click) and Double Click using the Actions class from the org.openqa.selenium.interactions package.


1. Right Click (Context Click) Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class RightClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html");

        // Find the element to right click
        WebElement element = driver.findElement(By.cssSelector(".context-menu-one"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Right Click (Context Click)
        actions.contextClick(element).perform();

        // Optional: Click on a menu item if needed
        WebElement menuItem = driver.findElement(By.cssSelector(".context-menu-item.icon-copy"));
        menuItem.click();

        driver.quit();
    }
}


font-size:14px;

2. Double Click Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DoubleClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/simple_context_menu.html");

        // Find the button to double-click
        WebElement button = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Double Click
        actions.doubleClick(button).perform();

        // Handle the alert
        driver.switchTo().alert().accept();

        driver.quit();
    }
}


Important Points:

  • You must call .perform() at the end to actually execute the action.

  • Make sure to import Actions class:

import org.openqa.selenium.interactions.Actions;

Actions Class in Selenium

 

In Selenium WebDriver (Java), the Actions class is used to handle complex user interactions and advanced gestures like mouse movements, key presses, drag-and-drop, right-clicks, double-clicks, etc.


Why Use Actions Class?

  • Simulate mouse and keyboard actions

  • Handle advanced interactions not possible with simple WebElement methods


Import Statement:

import org.openqa.selenium.interactions.Actions;


Creating an Actions Object:

Actions actions = new Actions(driver);
Where driver is your instance of WebDriver.


Common Methods of Actions Class:

MethodDescription
click()Clicks at the current mouse location
click(WebElement)Clicks on a given element
doubleClick() / doubleClick(element)Double-clicks
contextClick() / contextClick(element)Right-clicks
moveToElement(element)Moves mouse to element
dragAndDrop(source, target)Drags source to target
clickAndHold() / release()Click and hold / release
sendKeys(Keys.XXX)Sends keyboard keys


Most of these methods are chained and must be followed by .perform() to execute.


Example Code Snippets:

1. Mouse Hover

WebElement element = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(element).perform();

2. Right Click (Context Click)

WebElement element = driver.findElement(By.id("rightClickBtn"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

3. Double Click

WebElement element = driver.findElement(By.id("doubleClickBtn"));
Actions actions = new Actions(driver);
actions.doubleClick(element).perform();

4. Drag and Drop

WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();

5. Click and Hold / Release

Actions actions = new Actions(driver);
actions.clickAndHold(source).moveToElement(target).release().perform();


6. Keyboard Events Example:

actions.sendKeys(Keys.ENTER).perform();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();