2

I want to navigate Angular single page application without reloading the webpage. On button click I'm calling following code to navigate.

String fullUrl = "https://example.com/page1";
String hashUrl = "/page1";

public void goBackInWebView(String fullUrl, String hashUrl) {
    WebBackForwardList history = webview.copyBackForwardList();
    int index;
    int currentIndex = history.getCurrentIndex();
    for (int i = 0; i < history.getSize(); i++) {
        index = i - currentIndex;
        if ((webview.canGoBackOrForward(1 + i)) || (webview.canGoBackOrForward(1 - i))) {
            if (history.getItemAtIndex(i).getUrl().endsWith(hashUrl)) {
                webview.goBackOrForward(index);
                break;
            } else if (i == history.getSize()) {

                webview.loadUrl(fullUrl);
                break;
            }

        } else {
            //OUTER ELSE
            webview.loadUrl(fullUrl);
            break;
        }
    }
}

If the webpage is not saved in the history it will call webview.loadUrl(fullUrl); else it will load the page using webview.goBackOrForward(index);.

but is above code everytime OUTER ELSE is callling.

  • What you need to do is to create a WebViewFragment that takes your forward url and and open(load) it. You attach a new Fragment everytime there is a new forward URL by intercepting shouldOverrideUrl and on backpress just pop the fragment. :) That way you can also modify animations from one page to another. And you will get better hold on your Web Pages. – mudit_sen Sep 14 '20 at 07:30

2 Answers2

0

First of all canGoBackOrForward is used for Getting whether the page can go back or forward the given number of steps. as you mentioned in question your web page is single page so you don't need call this method. I think bellow code can solve your problem.

public void goBackInWebView(String fullUrl, String hashUrl) {

        WebBackForwardList history = webview.copyBackForwardList();

        if (history.getSize() == 0) {
            webview.loadUrl(fullUrl);
        }else {
            for (int i = 0; i < history.getSize(); i++) {

                if (history.getItemAtIndex(i).getUrl().endsWith(hashUrl)) {
                    webview.goBackOrForward(i);
                    break;
                } else {
                    webview.loadUrl(fullUrl);
                }


            }
        }
    }
0

I find it difficult to see much relation to Android and WebView, because the problem is SPA.

Better use hashtag # navigation for SPA, because this won't request anything server-side.
The point simply is, that the back button does not matter the least, while never navigating.
One just needs to bind JavaScript, which runs whenever window.location.hash changes.

Martin Zeitler
  • 49,224
  • 12
  • 97
  • 156