javahtmlunit

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


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?

Solution

  • 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)