简体   繁体   English

无法使用Java将值设置为JxBrowser localstorage

[英]Cannot set values to JxBrowser localstorage using java

I want to set the language to the browser when it's loading and for that I'm setting the 'language' value to the browser's local storage. 我想在加载时为浏览器设置语言,为此,我将“语言”值设置为浏览器的本地存储。

Here is the browser initializing code. 这是浏览器的初始化代码。

BrowserPreferences.setChromiumSwitches("--disable-web-security",
        "--allow-file-access-from-files");

String randomStr = UUID.randomUUID().toString();
jxbrowserDataDirPath = BrowserPreferences.getDefaultChromiumDir() + "\\" + randomStr;

browser = new Browser(BrowserType.LIGHTWEIGHT, new BrowserContext(new BrowserContextParams(jxbrowserDataDirPath)));
final BrowserView browserView = new BrowserView(browser);
browser.setDialogHandler(new DefaultDialogHandler(browserView));
browser.setPopupHandler(new DefaultPopupHandler());

browser.getCacheStorage().clearCache();
this.add(browserView, BorderLayout.CENTER);

and after initializing the browser I'm loading the web page by URL and then set the value to local storage. 初始化浏览器后,我通过URL加载网页,然后将该值设置为本地存储。

browser.loadURL("file:///" + FILE_LOCATION + File.separator + "setting.html"); 
browser.getLocalWebStorage().setItem("language", "en");

But that value is not setting to local storage and I want to know the reason for this behavior ? 但是该值未设置为本地存储,我想知道这种现象的原因吗?


Furthermore when I use a browser loadListner it works fine 此外,当我使用浏览器loadListner时,它工作正常

browser.addLoadListener(new LoadAdapter()
    {
      @Override
      public void onDocumentLoadedInFrame(FrameLoadEvent arg0)
      {
        setLocalStorageValue(key, value);
      }
    });

but I cannot use the loadListner to my code for some reasons so that I'm trying to set the value after loading the browser. 但是由于某些原因,我无法在代码中使用loadListner,因此我试图在加载浏览器后设置该值。

Web Local Storage is accessible only after an HTML page is fully loaded and JavaScript context initialized on it. 仅在完全加载HTML页面并在其上初始化JavaScript上下文之后,才能访问Web Local Storage。 So to use Web Local Storage you need to be sure that HTML page is loaded. 因此,要使用Web Local Storage,您需要确保已加载HTML页面。

In the same time, the Browser.loadURL method is invoked asynchronously. 同时, Browser.loadURL方法被异步调用。 To make sure that the web page is loaded completely, you have to use the LoadListener.onFinishLoadingFrame() event. 为了确保网页完全加载,您必须使用LoadListener.onFinishLoadingFrame()事件。

So, your issue happens because browser.getLocalWebStorage().setItem("language", "en"); 因此,发生问题是因为browser.getLocalWebStorage().setItem("language", "en"); was called before page loading. 在页面加载之前被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM