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

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

问题描述

我有一个WebView,其中加载了带有自定义链接(例如app://action)的页面.我在清单文件中注册了网址方案,当我单击链接时,将使用正确的数据调用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加载网址?

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参考

更新:方法

Updates: Method shouldOverrideUrlLoading(WebView, String) is deprecated in API level 24. Use shouldOverrideUrlLoading(WebView, WebResourceRequest) instead.

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

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