问题
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