为什么我无法在 android studio 的字符串变量中访问 localStorage?

Why can't I access localStorage in a string variable on android studio?

我有一个非常基本的 webview 应用程序代码:

package com.budget.noname.budget;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String data = "<p id='v'></p><script>x=3; y=5; m=0; document.getElementById('v').innerHTML = m;</script>";
        WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);
        WebSettings webSettings = simpleWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDomStorageEnabled(true);
        //simpleWebView.loadUrl("file:///android_asset/index.htm");
        simpleWebView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", "");

    }
}

如果我将我的网络应用程序 (index.htm) 放在资产文件夹中并加载它,它可以完美运行,但我的代码可供任何关心提取 .apk 的人使用。

我试图将代码粘贴到字符串上并使用 loadDataWithBaseURL 加载它。它的效果几乎一样。问题是:如果我尝试访问 localStorage,代码就会中断。这是为什么?

示例:

String data = "<script>x=localStorage.getItem('name');</script>";

无效!!!虽然,正如我所说,如果我从资产文件夹加载相同的代码,它就可以工作。

就像已经:

The access to localStorage is only allowed on pages from certain "Web-safe" schemes, like http:, https: and file:. It doesn't work for about: and data: schemes for example, or for any custom scheme you might be using.

如果你看一下the loadDataWithBaseURL()'s docs,我们可以看到下面对baseUrl参数的声明:

String: the URL to use as the page's base URL. If null defaults to 'about:blank'.

这解释了为什么只有您的 file:/// 示例有效,并且还意味着您必须向该参数传递一些有效的内容。你可以加载任何你想要的URL,比如:

webView.loadDataWithBaseURL("http://google.com", data, "text/html", "UTF-8", "");

甚至 http://localhost:80 也能正常工作。


但是,这不会使您的 localStorage 值可用于 WebView 的其他实例(默认情况下它们不会在 Android 上进行对话)。一个常见的选择是使用另一个为您抽象它的库,例如 AndroidLocalStorage,例如