Selenium-java: Get session / local storage data

It is important to check session and local storage while testing web browser functionalities.
As part of test automation, sometimes we feel the need of getting certain data from session or local storage.

For example: access token can be obtained from the browser session or local storage.

There different ways to do that using Selenium.

1- Using Augmenter

//import packages
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.html5.LocalStorage;
import org.openqa.selenium.html5.SessionStorage;
import org.openqa.selenium.html5.WebStorage;
import org.openqa.selenium.remote.Augmenter;

WebDriver driver = new ChromeDriver();
WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);
// using local storage
LocalStorage localStorage = webStorage.getLocalStorage();

// using session storage
SessionStorage sessionStorage = webStorage.getSessionStorage();

2- Using Javascript executor

//import packages
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;

//Session storage
String sessionStorage= (String) jsExecutor.executeScript(String.format("return window.sessionStorage.getItem('%s');", "token"));

tring localStorage= (String) jsExecutor.executeScript(String.format("return window.localStorage.getItem('%s');", "token"));

This will print the json value as shown as the above picture.


Now we can parse this string to json object and extract the access_token value.

Leave a Reply