Note: Advice in this article will only work for JxBrowser 6. See the corresponding article for JxBrowser 7 here.(注意:本文中的建议仅适用于JxBrowser6,JxBrowser7相应文章请点击这里。)


HTML5 supports Web Storage API that allows browsers to store key/value pairs, in a much more better way than using cookies. Web Storage API provides two mechanisms of storing data locally:(HTML5支持Web存储API,该API允许浏览器以比使用cookie更好的方式存储键/值对。 Web Storage API提供了两种在本地存储数据的机制:)

  • window.localStorage stores data with no expiration date.(window.localStorage存储没有到期日期的数据。)
  • window.sessionStorage stores data for one session (data is lost when the browser tab is closed).(window.sessionStorage存储一个会话的数据(关闭浏览器选项卡时数据丢失)。)

JxBrowser provides API that allows working with both Local and Session storages. See the following methods:
  • Browser.getLocalWebStorage() returns Local web storage instance.(Browser.getLocalWebStorage()返回本地Web存储实例。)
  • Browser.getSessionWebStorage() returns Session web storage instance.(Browser.getSessionWebStorage()返回会话Web存储实例。)

Local and Session storages implement same WebStorage interface that provides methods for working with storage.(本地存储和会话存储实现相同的WebStorage接口,该接口提供了使用存储的方法。)

Important: the Browser.getLocalWebStorage() method returns null if JavaScript hasn't accessed the localStorage variable. The reason is that there's a lazy initialization of the local storage in Chromium engine. You need access the localStorage variable in JavaScript to initialize local storage. After that you can access it via JxBrowser Web Storage API. It's a limitation in the current implementation. The following code snippet demonstrates how to workaround this limitation:(重要提示:如果JavaScript尚未访问localStorage变量,则Browser.getLocalWebStorage()方法将返回null。原因是Chromium引擎中的本地存储存在延迟的初始化。您需要访问JavaScript中的localStorage变量以初始化本地存储。之后,您可以通过JxBrowser Web Storage API访问它。这是当前实施中的限制。下面的代码片段演示了如何解决此限制:)

browser.addLoadListener(new LoadAdapter() {
    @Override
    public void onDocumentLoadedInMainFrame(LoadEvent event) {
        Browser browser = event.getBrowser();
        // Initialize WebStorage
        browser.executeJavaScript("localStorage");
        
        // Access WebStorage
        WebStorage webStorage = browser.getLocalWebStorage();
        // Read and display the 'myKey' storage value.
        String itemValue = webStorage.getItem("myKey");
    }
});


The following sample demonstrates how to access Local web storage of the loaded web page, read and set key/value pairs: (以下示例演示如何访问已加载网页的本地Web存储,读取和设置键/值对)
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.LoadHTMLParams;
import com.teamdev.jxbrowser.chromium.LoggerProvider;
import com.teamdev.jxbrowser.chromium.WebStorage;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.events.LoadEvent;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;

/**
 * The sample demonstrates how to access WebStorage on
 * the loaded web page using JxBrowser API.
 */
public class WebStorageSample {
    public static void main(String[] args) {
        LoggerProvider.setLevel(Level.OFF);

        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onDocumentLoadedInMainFrame(LoadEvent event) {
                Browser browser = event.getBrowser();
                WebStorage webStorage = browser.getLocalWebStorage();
                // Read and display the 'myKey' storage value.
                System.out.println("The myKey value: " + webStorage.getItem("myKey"));
                // Modify the 'myKey' storage value.
                webStorage.setItem("myKey", "Hello from Local Storage");
            }
        });

        browser.loadHTML(new LoadHTMLParams(
                "<html><body><button onclick=\"myFunction()\">" +
                        "Modify 'myKey' value</button>" +
                        "<script>localStorage.myKey = \"Initial Value\";" +
                        "function myFunction(){alert(localStorage.myKey);}" +
                        "</script></body></html>",
                "UTF-8",
                "http://teamdev.com"));
    }
}