主要分三步:

  1. 写个接口,接收 Js 回调
  2. 添加到 WebView
  3. 主动调用 Js 获取

比如我要获取保存在 LocalStorage 中的 userKey 字段:

1.写个接口,接收 Js 回调

public class HybridInterface {
    Context context;

    InitCityInterface(Context context) {
        this.context = context;
    }

    //Js 回调方法,
    @JavascriptInterface
    public void getUserKey(String userKey){
        LogUtils.e("WebViewFragment","读取到userKey : " + userKey);
        //已经拿到值,进行相关操作
    }

}

2.添加到 WebView ,并且重命名为“shixintest”:

mWebView.addJavascriptInterface(new HybridInterface(getActivity()), "shixintest");

3.主动调用 Js 获取
/**
* 获取 H5 保存在 LocalStorage 中的 __UserKey
*/

private void getLocalStorageUserKey() {
    if (mWebView != null && TextUtils.isEmpty(APPEnvironment.getBeforeLoginUserKey())) {
        mWebView.loadUrl(
            "javascript:(function(){
                var localStorage = window.localStorage; window.shixintest.getUserKey(localStorage.getItem('userKey'))})()");
}
}

getLocalStorageUserKey() 会通过 Js 读取 LocalStorage 的内容,然后通过 HybridInterface 传递过来。

就酱紫拿到了 LocalStorage 中的内容。

相关文章:

  • 2022-01-12
  • 2022-12-23
  • 2022-02-12
  • 2022-12-23
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-21
  • 2021-07-05
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
相关资源
相似解决方案