Is there a way to pass result of localstorage:getItem() to activity from webview

不羁岁月 提交于 2019-12-24 18:54:19

问题


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 +"')");

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


回答1:


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 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
}
}

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+"')");

                }
            });

And then call this method from your js like:

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


来源:https://stackoverflow.com/questions/55508774/is-there-a-way-to-pass-result-of-localstoragegetitem-to-activity-from-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!