I want to log the history url or last loaded url without manually storing the history urls. Is that possible?
Asked
Active
Viewed 1.9k times
2 Answers
37
Found the answer in the docs ...
WebBackForwardList mWebBackForwardList = mWebView.copyBackForwardList();
String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()-1).getUrl();

Arnab Chakraborty
- 7,442
- 9
- 46
- 69
-
It works but there is a mistake. If you are on PageA then you go to PageB. Now when you press back button it takes you correctly back to pageA. But now if you press back button again, it will take you to PageB again because pageB was the previous page. So, it will loop between the two pages forever. – Adil Malik Jul 29 '13 at 01:31
-
1In any case I wasn't using the history to navigate to pages, so it wouldnt be an issue in my case. I just needed it for logging purposes. Are you using the backForwardList to navigate? If so, why? Android browser would take care of that by default, wouldnt it? – Arnab Chakraborty Aug 01 '13 at 14:11
-
I had to implement a very simple browser. I used this instead: `if(browser.canGoBack()){ browser.goBack() }else{ finish() }` This worked fine for me. – Adil Malik Aug 01 '13 at 18:09
0
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);
}
}

tarrant
- 2,633
- 1
- 17
- 10
-
onPageFinished tends to get called multiple times per page, particularly if there is redrawing (eg blinking cursors) or iframes. You could also shouldOverrideUrlLoading, which only gets called for a new URL, but that doesn't get called for iframes. So the best approach is to use a combination of use onPageFinished and shouldOverrideUrlLoading as described at http://stackoverflow.com/questions/3149216/how-to-listen-for-a-webview-finishing-loading-a-url-in-android – Torid Oct 13 '11 at 17:09
-
Yep, true. You'd have to see if the url was in the list already (at the zeroth position) and not add it in that case. – tarrant Oct 13 '11 at 17:20
-
I guess I didn't make myself clear, I **don't** want to manually save the urls. The webview does maintain a history stack, right? I just want to get the last loaded url. – Arnab Chakraborty Oct 14 '11 at 04:35