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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章