如何拦截 WebView (android) 中的 url 加载? [英] How to intercept url loads in WebView (android)?

查看:115
本文介绍了如何拦截 WebView (android) 中的 url 加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WebView,我在其中加载了一个带有自定义链接(如 app://action)的页面.我在清单文件中注册了 url 方案,当我点击链接时,我的 Activity 的 onResume() 方法被调用了正确的数据并且它工作正常.

I have a WebView in which I load a page with a custom link (like app://action). I registered the url schemes in the manifest file and when I click on the link, the onResume() method of my Activity is called with the correct data and it works OK.

我的问题是 WebView 仍然尝试加载链接,而我的 WebView 最终显示网页不可用"消息.我不想那样.

My problem is that the WebView still try to load the link and my WebView ends up to show a "Web page unavailable" message. I don't want that.

如何阻止 WebView 加载 url?

How can I prevent the WebView to load the url?

这是我的代码:

WebView banner = ...
banner.setWebViewClient(new WebViewClient() {

    @Override
    public void onLoadResource(WebView view, String url) {

        if (url.startsWith("app://")) {

            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url), getContext(), Main.class);
            //startActivity(i);
        }
    }
}

banner.loadUrl("url_to_the_banner");

推荐答案

改用 WebViewClient.shouldOverrideUrlLoading.

Use WebViewClient.shouldOverrideUrlLoading instead.

public boolean shouldOverrideUrlLoading(WebView view, String url){
    // handle by yourself
    return true; 
}

WebViewClient 参考

更新: 方法 shouldOverrideUrlLoading(WebView, String) 在 API 级别 24 中已弃用.使用 shouldOverrideUrlLoading(WebView, WebResourceRequest).

这篇关于如何拦截 WebView (android) 中的 url 加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆