Home » Android » java – webView.canGoBack() always false

java – webView.canGoBack() always false

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a problem with Android Web View.
When I override the function shouldOverrideUrlLoading in my class that extends WebViewClient then WebView.canGoBack() returns always false.

Below is my code

public class SMWebViewClient extends WebViewClient {

   @Override
   public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
      view.loadUrl(request.getUrl().toString());
      return true;
   }

   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String uri) {
      view.loadUrl(uri);
      return true;
   }
}

And in the my activity:

@BindView(R.id.main_webview) SMWebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...
    webView.setWebViewClient(new SMWebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url){

        }
    });
    webView.clearCache(true);
    webView.clearHistory();
    webView.loadUrl(Constant.baseUrl + Constant.homeUrl);
}

The problem is that the function webView.canGoBack (always in my activity) returns always false:

    @Override
    public void onBackPressed() {
       //ALWAYS FALSE
       if (webView.canGoBack()) {
          webView.goBack();
       }
    } 

If I don’t override shouldOverrideUrlLoading, than onBackPressed works as expected. What is wrong in my code?

Thanks

[EDIT]: I also tried (without success) to create webViewClient in this way:

ebView.setWebViewClient(new SMWebViewClient());
How to&Answers:

There seems to be a problem with current release of Chrome (63+).
I downloaded Chrome Dev (65+), change the default webview to Chrome Dev 65+, the webview.canGoBack() works fine.

Here is some reading of bug reported:
https://bugs.chromium.org/p/chromium/issues/detail?id=794020

Chrome Dev download URL:
https://play.google.com/store/apps/details?id=com.chrome.dev

Changing default webview:
https://www.chromium.org/developers/androidwebview/android-webview-beta

Looks like we need to wait for somewhile for the new Chrome stable update.

Answer:

Do not load the url everytime in the WebClient this clears the past history of the WebView and also check how you extended the WebView to your own SMWebView.