There are two options to interact with browser’s local storage:
- via javascript by creating your own methods
- via Selenium WebDriver (starting with version 2.42) if the driver supports it
Let’s have a look of how can we use these two options in our Selenium WebDriver tests:
Are Your APIs as Reliable as You Think?
Don’t let hidden issues disrupt your service. With LoadFocus’s advanced API Monitoring, catch problems before they impact your users. Ensure flawless performance and avoid costly outages—monitor, test, and optimize your APIs effortlessly.
1. Let’s create a LocalStorage class with methods for each action we need for interaction with the browser’s Local Storage:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class LocalStorageJS {
private JavascriptExecutor js;
public LocalStorageJS(WebDriver webDriver) {
this.js = (JavascriptExecutor) webDriver;
}
public void removeItemFromLocalStorage(String item) {
js.executeScript(String.format("window.localStorage.removeItem('%s');", item));
}
public boolean isItemPresentInLocalStorage(String item) {
return !(js.executeScript(String.format("return window.localStorage.getItem('%s');", item)) == null);
}
public String getItemFromLocalStorage(String key) {
return (String) js.executeScript(String.format("return window.localStorage.getItem('%s');", key));
}
public String getKeyFromLocalStorage(int key) {
return (String) js.executeScript(String.format("return window.localStorage.key('%s');", key));
}
public Long getLocalStorageLength() {
return (Long) js.executeScript("return window.localStorage.length;");
}
public void setItemInLocalStorage(String item, String value) {
js.executeScript(String.format("window.localStorage.setItem('%s','%s');", item, value));
}
public void clearLocalStorage() {
js.executeScript(String.format("window.localStorage.clear();"));
}
}
2. Using the Selenium WebDriver built in functionality present in the HTML5 package
Think your website can handle a traffic spike?
Fair enough, but why leave it to chance? Uncover your website’s true limits with LoadFocus’s cloud-based Load Testing for Web Apps, Websites, and APIs. Avoid the risk of costly downtimes and missed opportunities—find out before your users do!
(org/seleniumhq/selenium/selenium-api/2.45.0/selenium-api-2.45.0.jar!/org/openqa/selenium/html5)
Clearing LocalStorage:
LocalStorage local = ((WebStorage) driver).getLocalStorage();
local.clear();
Setting an item in LocalStorage:
local.setItem("FOO", "BAR");
Getting an item from LocalStorage:
local.getItem(“name”)
Here you can find more details about locating elements with Selenium WebDriver.
LoadFocus is an all-in-one Cloud Testing Platform for Websites and APIs for Load Testing, Apache JMeter Load Testing, Page Speed Monitoring and API Monitoring!