Find out where in browser history the user is

2019-06-26 04:21发布

问题:

I know I access browser history using history object, specifically, I can use history.back();, history.forward(); and history.go(item-number) (or history.go(url)). What I am trying to determine where in the browser history the user currently is.

Firefox, for example, may support accessing individual url's from the history, but that's not what I'm after, because the history of 20 url's may contain repeated url's.

Note that I am not interested in a history within my project - but rather browser history within any user's session.

For example, a user opened the browser and went through 20 pages - so the history contains 20 objects. Then the user hit back button 4 times - and ended up on the 16th of the 20 pages (or rather 15th of the 0..19 pages). Is there any way to get this current offset (16 or 15) using JavaScript? If yes, then how?

回答1:

history.length

returns the length of the current history.

sadly there is no method to figure out where in it you are.



回答2:

Don't know if this will help, but with HTML5 you can add a state object to each item in the browser history list. This gives you a possible way to save each item's index (i.e., its history.length value at the time it is first created), which you can then examine later.

This is the only solution I found that worked for me.

See my solution here for more details.