Test sessionStorage with Selenium Webdriver
Asked Answered
A

2

5

I'm writing Java based selenium-webdriver tests. The app that I'm testing sets certain values in storageSession e.g. sessionStorage.setItem("demo", "test"), how can I check and assert the value of the stored variable demo inside my test

Anklet answered 19/12, 2014 at 11:43 Comment(2)
Is that stored in a cookie? if so then u can get that cookie and then from cookie u can get that variableForesheet
thanks, but nope its not inside the cookie, rather stored within a browser's sessionStorageAnklet
A
13

Found a great utility class https://gist.github.com/roydekleijn/5073579

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

public class LocalStorage {
  private JavascriptExecutor js;

  public LocalStorage(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();"));
  }
}

thanks Roy

Anklet answered 19/12, 2014 at 12:24 Comment(4)
Python please. I am looking to access the Session Storage and return some files. Help!Elemi
Thank you very much. This really helped me pass through a difficult situation. I was trying to get items from local storage, this method worked for me.Godber
This is great for local storage but it's missing the equivalent for session storage.Cariole
This is the one for session storage public String getItemFromSessionStorage(String key) { return (String) js.executeScript(String.format( "return sessionStorage.getItem('%s');", key)); }Cariole
C
0

Expanding on the answer from @learnAndImprove which shows how to retrieve the local storage info, here is the piece we can add to that class to get the session storage.

public String getItemFromSessionStorage(String key) {
    return (String) js.executeScript(String.format(
            "return sessionStorage.getItem('%s');", key));
}
Cariole answered 23/8, 2022 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.