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:

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


(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.

P.S.: LoadFocus is a cloud testing platform. Try it for free.

How Much Traffic Can Your Website Handle?