Selenium + Java · Lesson 33 of 44

0/44 done

Module 33: Cookies & Browser Storage

33. Managing Cookies, Session Injection & LocalStorage

15 minlesson

Your task

Implement injectAuthCookie:

  1. Accept WebDriver driver, String name, and String value.
  2. Call driver.manage().addCookie(new Cookie(name, value)).

Write it in the editor, then press Check answer (Ctrl + Enter).

java
import org.openqa.selenium.Cookie;

// Add session cookie:
Cookie authCookie = new Cookie("session_token", "jwt_abc123");
driver.manage().addCookie(authCookie);
driver.navigate().refresh(); // Apply cookie

// Clear cookies:
driver.manage().deleteAllCookies();

// LocalStorage via JavaScriptExecutor:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("localStorage.setItem('theme', 'dark');");
String token = (String) js.executeScript("return localStorage.getItem('token');");

Key Takeaways & Walkthrough Summary

Manipulating cookies and browser storage allows you to bypass repeated UI logins and set feature flags directly. In this lesson, you will master driver.manage().getCookies(), adding session tokens, and clearing cookies. Let's manage cookies!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why does addCookie() throw InvalidCookieDomainException?

You must navigate to the application domain first using driver.get() before adding cookies for that domain.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip