我有一个非常基本的 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) 放在 Assets 文件夹中并加载它,它会完美运行,但我的代码可供任何关心提取 .apk 的人使用。
我试图将代码粘贴到字符串上并使用 loadDataWithBaseURL 加载它。它的效果几乎一样。问题是:如果我尝试访问 localStorage,代码就会中断。这是为什么?
例子:
String data = "<script>x=localStorage.getItem('name');</script>";
没用!!!虽然,正如我所说,如果我从 Assets 文件夹加载相同的代码,它就可以工作。
最佳答案
就像已经stated here before :
The access to
localStorage
is only allowed on pages from certain"Web-safe"
schemes, likehttp:
,https:
andfile:
. It doesn't work forabout:
anddata:
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 ,例如
关于javascript - 为什么我不能在 android studio 的字符串变量中访问 localStorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582243/