Android WebView : Navigate to Url Hash without reloading using goBackOrForward

Viewed 296

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.

2 Answers

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);
                }


            }
        }
    }

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.

Related