在Webview中从LocalStorage读取数据

时间:2019-01-18 07:06:12

标签: javascript android webview

我在应用程序中使用了Webview,我已成功将数据写入本地存储,但是我想从中读取其他数据。这是代码

private WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    webView = findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            String key = "key";
            String value = "value";
            String loc;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.evaluateJavascript("localStorage.setItem('" + key + "', '" + value + "');", null);
                webView.evaluateJavascript("localStorage.getItem('" + key + "');", null);
            }
            else {
                webView.loadUrl("javascript:localStorage.setItem('" + key + "', '" + value + "');");
                webView.loadUrl("javascript:localStorage.getItem('" + key + "');");
            }
        }

        /*@Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            String key = "key";
            String value = "value";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.evaluateJavascript("localStorage.setItem('" + key + "', '" + value + "');", null);
            }
            else {
                webView.loadUrl("javascript:localStorage.setItem('" + key + "', '" + value + "');");
            }
        }*/
    });
    webView.loadUrl(<some_website>);
}

我可以使用evaluateJavascript函数读取值吗?或其他任何方式...

0 个答案:

没有答案