我有一个 webview android 应用程序,它打开一个包含一些 HTML5/JavaScript 代码的网页。我想将一些值从我的应用程序的 android 端传递到浏览器端。所以我想从 Android 写入 HTML5 localstorage,然后网页的 Javascript 部分从 localstorage 读取值。
Android webview 如何写入 HTML5 localstorage?
或者有什么方法可以让 android 将一些值传递给它加载的页面的 javascript? (无需重新加载整个页面)假设在 HTML5 localstorage 上写一些东西,然后 javascript 代码从 HTML5 localstorage 中读取那个东西
它不同于how to pass json formatted data from a webview to a html page .我需要一种通过 android 写入 HTML5 本地存储的方法
最佳答案
像字符串一样传递变量stackoverflow post :
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
String key = "hello";
String val = "world";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("localStorage.setItem('"+ key +"','"+ val +"');", null);
} else {
webView.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ val +"');");
}
}
});
第二种变体是使用 JavaScriptInterface
初始化部分
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
JavaScript 接口(interface)
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public string getData(String someParameter){
//also you can return json data as string and at client side do JSON.parse
if (someParameter == "give me data" && this.activity.data) {
return this.activity.data;
}else{
return null;
}
}
}
JS部分
<script>
function ready() {
var data = window.JSInterface.getData("give me data");
localStorage.put("give me data", data)
};
document.addEventListener("DOMContentLoaded", ready);
</script>
关于javascript - Android 如何将值写入 HTML5 localstorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054224/