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();
localStorage.getItem("token");

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

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"));
System.out.println(sessionStorage);

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

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

{“access_token”:”00Dg0000006I2Oa!AQkAQAzQYGM6f_ihsrTMPSDxccExUCmw4q5wlJDIBgMn1RLvdYZeMwn194o71pPTpSdYHG63nVmOxVKU3xSaXCKQNDsJh6r2″,”received_at”:1586876101101}

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

Leave a Reply