How to detect errors from home page only in new onReceivedError from WebViewClient
Context
Android SDK 23 is onReceivedError(WebView view, int errorCode, String description, String failingUrl)
deprecated and replaced with onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
. However, according to the documentation :
Note that unlike the legacy version of the callback, the new version will be called for any resource (iframe, image, etc.), not just the main page
Problem
We have an application where, in a legacy method, onReceivedError
there is code to display a native view instead of letting the user see the error in the WebView.
We would like to replace the deprecated method with a onReceivedError
new method. But we don't want to display our own kind of errors for any resource, only for the main page.
Question
How can we identify in the new onReceivedError
that the error is not from the main page?
PS 1: We would rather not have a solution like this to keep the main url and check for no url.
PS 2: If the solution is to simply use the legacy method, what guarantee is it that it will still be called for newer versions of Android?
source to share
WebResourceRequest
has a method isForMainFrame()
for your script that is available since API version 21:
Source: https://developer.android.com/reference/android/webkit/WebResourceRequest.html
source to share
You don't need to keep the original url. You can get it from WebView
passed to the method onReceivedError
. This is always the full URL of the current page that the user sees. This way you don't have to worry about them going to different pages.
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.getUrl().toString().equals(view.getUrl())) {
notifyError();
}
}
source to share
you can use like codes:
WebView wv = (WebView) findViewById(R.id.webView);
wv.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.i("WEB_VIEW_TEST", "error code:" + errorCode);
// here your custom logcat like as share preference or database or static varible.
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
Good luck!
source to share