Disable Android WebView/WebViewClient Initiated favicon.ico Request

后端 未结 5 872
独厮守ぢ
独厮守ぢ 2021-01-11 16:27

How can I disable the Android WebView/WebViewClient from sending out a request for favicon.ico when I call WebView.loadUrl()? I can see the call being made while profiling r

5条回答
  •  情话喂你
    2021-01-11 17:16

    I achieved this by a little hack. First, I've created a fake 1x1 icon file and saved it to the assets folder. Then I overrode WebViewClient's shouldInterceptRequest() method, where I check the URL whether it is the request for favicon file and in that case return WebResourceResponse with InputStream which contains our fake icon:

        @Override
        @CallSuper
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if(!request.isForMainFrame() && request.getUrl().getPath().equals("/favicon.ico")) {
                try {
                    return new WebResourceResponse("image/png", null, new BufferedInputStream(view.getContext().getAssets().open("empty_favicon.ico")));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    

    Note that the InputStream must not be closed in our code, because it is subsequently used by the WebView to read the icon. The WebviewClient must be set to the WebView via its setter:

    mWebView.setWebViewClient(subclassedWebViewClient);
    

提交回复
热议问题