Disable Android WebView / WebViewClient Initiated request favicon.ico

How to disable Android WebView / WebViewClient from sending a request to favicon.ico when calling WebView.loadUrl ()? I see that the call is being made while profiling requests through CharlesProxy.

I do not own the HTML content that I display in the WebView. My research has received many results on server side workarounds, but this will not work for me.

+7
android favicon android-webview webviewclient
source share
3 answers

I achieved this with a little hack. First, I created a fake 1x1 icon file and saved it in the resources folder. Then I tried the WebViewClient shouldInterceptRequest () method , where I check the URL whether this is a request for the favicon file, in which case it returns a WebResourceResponse with an InputStream that 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; } 

Please note that InputStream should not be closed in our code, because it is subsequently used by WebView to read the icon. WebviewClient must be installed in WebView through its setter:

 mWebView.setWebViewClient(subclassedWebViewClient); 
+5
source share

for me the complete solution was:

  @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if(url.toLowerCase().contains("/favicon.ico")) { try { return new WebResourceResponse("image/png", null, null); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override @SuppressLint("NewApi") public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if(!request.isForMainFrame() && request.getUrl().getPath().endsWith("/favicon.ico")) { try { return new WebResourceResponse("image/png", null, null); } catch (Exception e) { e.printStackTrace(); } } return null; } 
+5
source share

There is a method for the WebView class named getFavicon (). I think this method is called by WebView to retrieve the icon from the server by issuing a request. Therefore, you can try to extend the WebView class and override the getFavicon () method to do nothing. I have not tried it myself, but it might work.

-2
source share

All Articles