Android强制使用WebView不调用系统或外部浏览器

在HTML5混合APP开发中,Android系统默认会在H5页面打开第三方链接时跳转到系统或外部浏览器。要避免这种情况,可以通过自定义WebViewClient并重写shouldOverrideUrlLoading方法,返回True,使得WebView内部加载所有URL。这样可以确保所有链接在WebView内处理,而不是交给系统。需要注意的是,对于如tel:和mailto:等特殊URL,需要进行额外处理以防止意外行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
});




原因可以从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;
}


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



--------------------------------------------------------------------------------------

- 版权声明:

- 如在本页面内无特别说明,本文内容均为[李大仁博客]原创,本文版权归[李大仁博客]所有。

- 欢迎转载,转载请务必在文章页面明显位置提供原文链接并注明出处。欢迎您在转载本文时保留本段声明。

- 文章标题: Android强制使用WebView不调用系统或外部浏览器

- 独立博客: 李大仁博客

- 永久链接: http://www.lidaren.com/archives/1583

--------------------------------------------------------------------------------------

以上内容由博客自动发布工具自动发布,最终显示内容和效果会与原文内容有所偏差,敬请谅解。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值