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.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 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. – adeneo Jun 30 '15 at 16:24
  • The top answer here http://stackoverflow.com/questions/829046/how-do-i-detect-if-a-user-has-got-to-a-page-using-the-back-button suggests using a hidden form since those values are preserved – bbill Jun 30 '15 at 16:25
  • 1
    Try the `unload` event: https://developer.mozilla.org/en-US/docs/Web/Events/unload. Also see this similar question: http://stackoverflow.com/questions/1341089/using-meta-tags-to-turn-off-caching-in-all-browsers – Pluto Jun 30 '15 at 16:25

2 Answers2

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.

arthurakay
  • 5,631
  • 8
  • 37
  • 62
  • Yeah, that's nice. I can compare localStorage.historyLength to window.history.length. Works for me! – Phillip Senn Jun 30 '15 at 16:37
  • Except it doesn't work if they press forward and back again. – Phillip Senn Jun 30 '15 at 16:43
  • 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. – arthurakay Jun 30 '15 at 17:05
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()
}
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373