Find out if Android WebView shows a cached page

I am making an Android app that, among other things, displays websites in a webview. As I understand it, web browsing automatically shows a cached version of the page if the connection cannot be established.

Is there any way to find out if the page was displayed from the server or cache?

Maybe even how old is the cached page.

This means that you can notify the user if he is viewing old information.

+6
source share
2 answers

You can try to hack - first set WebView caching mode to WebSettings.NO_CACHE and load the URL. Then create your own WebChromeClient as follows:

 final String urlToLoad = "http://www.my-url.com"; webview.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { if (view.getSettings().getCacheMode() == WebSettings.LOAD_NO_CACHE && urlToLoad.equals(failingUrl)) { view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); view.loadUrl(urlToLoad); return; } else if (urlToLoad.equals(failingUrl)) { // cache failed as well, load a local resource as last resort // or inform the user } super.onReceivedError(view, errorCode, description, failingUrl); } }); webview.loadUrl(urlToLoad); 
+7
source

Since WebView works like a browser, the answer is no. There is some hacker way to detect this situation.

Or an alternative solution will prevent page caching (see the WebView documentation).

0
source

Source: https://habr.com/ru/post/889005/


All Articles