Home » Android » webkit – Get last loaded url of webview without doing a webView.goBack() in Android

webkit – Get last loaded url of webview without doing a webView.goBack() in Android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to log the history url or last loaded url without manually storing the history urls. Is that possible?

How to&Answers:

Found the answer in the docs …

WebBackForwardList mWebBackForwardList = mWebView.copyBackForwardList();
String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()-1).getUrl();

Answer:

You could maintain a stack(list) of URL’s visited by adding them in onPageFinished() and removing them when the user backs up.

i.e.

private List<String> urls = new ArrayList<String>();

        @Override
    public final void onPageFinished(final WebView view,final String url) {
                     urls.add(0, url);
        super.onPageFinished(view, url);
    }

and then trap the back key in the activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {

    case KeyEvent.KEYCODE_BACK:
                    if (urls.size() == 1) {
            finish();
            return true;
        } else if (urls.size() > 1) {
            urls.remove(0);

            // load up the previous url
            loadUrl(urls.get(0));

            return true;
        } else
                            return false;
    default:
        return super.onKeyDown(keyCode, event);
    }
}