How to load a "local storage" value to HtmlUnit web client?

65 Views Asked by At

I'm trying to load a local storage value into the HtmlUnit web client before it loads a specific website:

HtmlPage initialPage = webClient.getPage(url);
        if (httpHeadersSpec != null && httpHeadersSpec.getLocal_storage() != null) {
            for (StorageItemSpec item : httpHeadersSpec.getLocal_storage()) {
                initialPage.executeJavaScript(
                        "localStorage.setItem('" + item.getKey() + "', '" + item.getValue() + "');");
            }
        }

HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScriptStartingBefore(3000);
URL baseUrl = page.getFullyQualifiedUrl(page.getBaseURI());

The problems are:

  1. How do I check if the local storage value is loaded?
  2. What is the correct approach to load a browser's local storage value to HtmlUnit before loading a page?
2

There are 2 best solutions below

0
RBRi On BEST ANSWER

Starting with version 3.4.0 there is a documented (https://www.htmlunit.org/details.html#Local.2FSession_Storage) way to do this.

try (WebClient webClient = new WebClient()) {

    // get the local storage for the url
    // the url has to match the page url you will load later
    final Map<String, String> localStorage = webClient.getStorageHolder().getLocalStorage(url);


    // place some data in the session storage
    localStorage.put("myKey", "myData");

    // load the page that consumes the session storage data
    webClient.getPage(url);

    // make sure the new data are in
    assertEquals("myNewData", localStorage.get("myNewKey"));
}

(Btw the latest 3.4.0-SNAPSHOT already constains this)

1
RBRi On

So far (HtmlUnit 3.3.0) there is no real public API to do interaction with the storage outside of the js support.

Please open an issue at github and we can work together to add some methods to support your case (and maybe some documentation also).