0

I don't want to detect if the user has pressed the back button on my page.

I want to detect if the user has pressed the back button on someone else's page and has gotten back to my page.

I need to reload the page if that's the case.

3
  • Unfortunately I don't think there is such an event, there's not even a seperate event for the back button on your own page. I think you'd have to store sessions and the adresses users are redirected to, and then within a certain timeframe check if the same user is referred from the same domain etc. but it sounds pretty complicated. Commented Jun 30, 2015 at 16:24
  • The top answer here stackoverflow.com/questions/829046/… suggests using a hidden form since those values are preserved Commented Jun 30, 2015 at 16:25
  • 1
    Try the unload event: developer.mozilla.org/en-US/docs/Web/Events/unload. Also see this similar question: stackoverflow.com/questions/1341089/… Commented Jun 30, 2015 at 16:25

2 Answers 2

1

You can play with window.history and maybe store some values for the user locally in localstorage or a cookie. (For reference, MDN article)

For example, check the value of window.history.length when the user is on your page; then navigate somewhere else; then hit "back" to return to your prior page. Now compare window.history.length again -- it is different (at least for me, in Chrome).

TL;DR - this won' t be a foolproof method, but it might be a good enough hack for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, that's nice. I can compare localStorage.historyLength to window.history.length. Works for me!
Except it doesn't work if they press forward and back again.
Yes, that's true. I don't know how likely that is though... but given the other possible answers (via the links posted in the comments to your OP) it seems like there isn't a completely foolproof method to accomplish this. You might combine approaches.
0

Here's what I ended up doing. It works, but let me know if you have a better solution:

window.addEventListener('unload', unload) function unload() { localStorage.setItem('reload',1) } var reload = localStorage.getItem('reload') reload = parseInt(reload,10) if (reload) { localStorage.setItem('reload',0) // false doesn't work here. window.removeEventListener('unload', unload) window.location.reload() } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.