HTML5 HYBIRD混合APP需要在H5页面中打开第三方网站(例如:百度),android默认不在当前WebView中打开,反而会调用系统或外部浏览器,解决办法是自己重写WebViewClient,覆盖shouldOverrideUrlLoading并让其返回True。

实现代码

mWebView.setWebViewClient(new WebViewClient() {

public boolean shouldOverrideUrlLoading(WebView view, String url)

{

// webview自己加载URL,让后通知系统不需要HandleURL

view.loadUrl(url);

return true;

}

});

mWebView.setWebViewClient(new WebViewClient() {

public boolean shouldOverrideUrlLoading(WebView view, String url)

{

// webview自己加载URL,让后通知系统不需要HandleURL

view.loadUrl(url);

return true;

}

});

原因可以从Android源代码中可知,True if the host application wants to leave the current WebView and handle the url itself, otherwise return false。

/** 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.

* This method is not called for requests using the POST "method".

@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.

*/

public boolean shouldOverrideUrlLoading(WebView view, String url) {

return false;

}

/** 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.

* This method is not called for requests using the POST "method".

@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.

*/

public boolean shouldOverrideUrlLoading(WebView view, String url) {

return false;

}

需要注意一点问题,如果你的代码中有拨打电话(tel:),发送邮件(mailto:)的话,需要在实现代码时对URL简单筛选一下才好

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐