h5 App通信 轻量级方式

一般在遇到h5主动通知App的需求,Android的同学可能会使用
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new JavaClass(this), "XXXX");
将方法暴露给JavaScript
这种方式与h5通信,但是这种方式在android4.2以前是有安全漏洞的,见下面源码注释:
这里写图片描述
除安全因素外还有其他不便之处,如需要App与h5有明确的协定,属于一定程度上地代码入侵。那么有没有更优雅地一点方式呢?答案是有的

那就是利用WebViewClient类
/** @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return True if the host application wants to leave the current WebView
*and handle the url itself, otherwise return false.
* @deprecated Use {@link #shouldOverrideUrlLoading(WebView, WebResourceRequest)
*shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead.
*/
@Deprecated
public boolean shouldOverrideUrlLoading(WebView view, String url) {
     return false;
}
根据注释可知上面的方法被推荐使用了,由下面的方法替代
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
      return shouldOverrideUrlLoading(view, request.getUrl().toString());
}


/**
* Give the host application a chance to take over the control when a new
* url is about to be loaded in the current WebView. If WebViewClient is not
* provided, by default WebView will ask Activity Manager to choose the
* proper handler for the url. If WebViewClient is provided, return true
* means the host application handles the url, while return false means the
* current WebView handles the url.
*
* <p>Notes:
* <ul>
* <li>This method is not called for requests using the POST &quot;method&quot;.</li>
* <li>This method is also called for subframes with non-http schemes, thus it is
* strongly disadvised to unconditionally call {@link WebView#loadUrl(String)}
* with the request's url from inside the method and then return true,
* as this will make WebView to attempt loading a non-http url, and thus fail.</li>
* </ul>
* </p>
给宿主应用程序在新的时候接管该控件的机会
Url即将加载在当前WebView时。如果没有提供WebViewClient的情况下,由当前WebView处理UrL。如果提供了WebViewClientreturn true
表示宿主应用程序处理Url,而return false表示当前WebView处理Url。
注意:使用post方式发起的url请求则不会触发回调
----------------------------------------------------------------
知道上面的方法后,我们就可以利用这个规则了,由h5方主动触发url请求从而达到通知:
window.location.href = `[scheme]://[host]/[path]?[query]`
scheme:唤起协议
host: 唤起指定host
path: 协议路径
query: 一些参数
大家看到这个肯定觉得眼熟,这不是通过scheme唤起应用或应用类某个页面吗?这里只是搬用了这个url规则过来,方便统一处理。
剩下的代码大家都知道怎么去写了,就是解析url,处理不同的case了,具体业务需求具体对待。
注:上述方案在Android、Ios是通用的,都有类似shouldOverrideUrlLoading的api

猜你喜欢

转载自blog.csdn.net/u012982629/article/details/80602619