问题
Context
In the Android SDK 23 onReceivedError(WebView view, int errorCode, String description, String failingUrl)
has been deprecated and replaced with onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
. However as per documentation:
Note that unlike the deprecated version of the callback, the new version will be called for any resource (iframe, image, etc), not just for the main page
Problem
We have an app where in the deprecated onReceivedError
method there is a code to display a native view instead of letting the user see the error in the WebView.
We would like to replace the deprecated onReceivedError
method by the new method. But we don't want to display the native view for errors for any resource, just 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 prefer not having a solution like this to store the main url and check it against the failing url.
PS 2: If the solution is to just use the deprecated method, what's the guarantee that it will still be called for new Android versions?
回答1:
WebResourceRequest
has isForMainFrame()
method for your scenario which is available starting from API version 21:
Source: https://developer.android.com/reference/android/webkit/WebResourceRequest.html
回答2:
You don't have to store the original URL. You can get it from the WebView
passed to the onReceivedError
method. It's always the full URL of the current page that the user sees. So, you don't have to worry about them navigating to different pages.
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.getUrl().toString().equals(view.getUrl())) {
notifyError();
}
}
回答3:
you can use like as 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);
}
});
Best of luck!
来源:https://stackoverflow.com/questions/44068123/how-to-detect-errors-only-from-the-main-page-in-new-onreceivederror-from-webview