1

I have a JS single-page app that uses the history API. A user lands on my page and navigates around, and a bunch of pushStates and replaceStates happen under the hood. All of the transitions happen in JS, no page reload happens. My question is that how can I detect if the user is back on the first location within my own app, that is, one more back button press will cause the browser to reload the previous page the user was on?

Thanks in advance!

geoffliu
  • 510
  • 3
  • 10
  • You could try handling `popState` events and check state data (in which you could keep stuff like page counters, markers, etc...). Or simply keep application state in some variable. Since no page reloads happen, that variable will not disappear. – ahwayakchih May 27 '16 at 12:52

2 Answers2

4

You can detect the transition with hooking on onpopstate event and checking, where the user actually navigates:

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate

Note however that if you'll try to stop such transition, this may be hard to do:

how to stop browser back button using javascript

Community
  • 1
  • 1
Tomas Kulich
  • 14,388
  • 4
  • 30
  • 35
0

You could use something like:

if(window.location == <the url of the root) {
    //Do stuff here
}
dane
  • 631
  • 6
  • 15
  • That could be not enough, for example: user could be going back to "homepage" through menu, without using "back" button. So "homepage" would be visited more than once in his "travel", and clicking "back" would not necessary mean that user will leave site. – ahwayakchih May 27 '16 at 12:54
  • What if the user goes from location A to B to A (by clicking on a link, not the back button)? – geoffliu May 27 '16 at 12:55