有没有办法将localstorage:getItem()的结果传递给WebView的活动 [英] Is there a way to pass result of localstorage:getItem() to activity from webview

查看:239
本文介绍了有没有办法将localstorage:getItem()的结果传递给WebView的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用webview在android中加载页面。页面加载后,将更新本地存储。我想从中检索数据。在kitkat上方,使用valuateJavascript能够获取数据。它有一个回调。问题是在kitkat以下的版本中,我必须为此使用loadUrl()。

Am using webview to load a page in android. Once the page is loaded, localstorage is updated. I want to retrieve data from it. Above kitkat, using evaluateJavascript am able to obtain the data. It have a callback. The problem is with versions below kitkat, where i have to use loadUrl() for it.

loadUrl("javascript:localStorage.getItem('"+ key +"')");

我想将getItem()函数返回的值传递给调用活动。

I want to pass the value returned by function getItem(), to calling activity.

推荐答案

您可以做到。首先,您需要像这样将javascript界面​​添加到Webview中。假设您正在某个名为FormDetailActivity的活动中加载url:

you can do it. First you need to add javascript interface to your webview like this. Lets say you are loading url in some activity called FormDetailActivity:

final FormBridge formBridge = new FormBridge(FormDetailActivity.this);
mWebView.addJavascriptInterface(formBridge, "Android");

formBridge是一个类的实例,其中编写了所有从js调用的方法。 / p>

formBridge is the instance of a class where all the methods are written that are being called from js.

public class FormBridge extends Activity {


private static final String TAG = "FormBridge";

Context mContext;


private FormDetailActivity mFormActivity;



/**
 * Instantiate the interface and set the context
 */
public FormBridge(Context c) {
    mContext = c;

    mFormActivity = (FormDetailActivity) mContext;

}



@JavascriptInterface
public String getLocalStorageFromJs(String someStringFromJs) {
    //here you'll get the string from js
}
}

的字符串并从Java传递密钥到您的js,您需要在js中制作一个方法来接受关键参数,然后您可以这样调用它:

And to pass the key from java to your js you need to make a method in js accepting key param and then you can call it like this:

mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
               view.loadUrl("javascript:getStringFromLocalStorage('"+key+"')");

                }
            });

然后从您的js中调用此方法,例如:

And then call this method from your js like:

function getStringFromLocalStorage(key){
   Android.getLocalStorageFromJs(localStorage.getItem(key));
}

这篇关于有没有办法将localstorage:getItem()的结果传递给WebView的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆