0

I am writing a Single Page Application in JavaScript. The URL changes but there are no page reloads. In my app I have a browser-like navigation with a back button, that actually runs window.back() . I also keep a backCounter variable (increased every time a user clicks on a link or goes back, listening to popstate) to make sure that the app back button doesn't let user go a blank tab.

I realise that ther are security implications when reading the history, and I have read answers here about it.

Question: is there a reliable way for me to know when the user has pressed "back" within the same SPA? I can think of two possible paths:

  • Neutralise. I could maybe neutralise the function of the back button by forcing a specific location on popstate

  • Integration. I would love to be able to know if the user has clicked on back or forward so that I can update backCounter accordingly.

...ideas?

Merc
  • 16,277
  • 18
  • 79
  • 122
  • Possible duplicate of [How to check if the user can go back in browser history or not](https://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not) – str Jun 28 '19 at 07:40
  • @str This is a completely different question about checking if the in-app back button would cause a navigation out of the SPA – Avin Kavish Jun 28 '19 at 07:41
  • "is there a reliable way for me to know when the user has pressed "back" within the same SPA?" Yes, the popstate event fires only when within the same SPA. You can update the counter in popstate. Push the counter in using pushState and you will get the correct counter back when pop state is fired. – Avin Kavish Jun 28 '19 at 07:47
  • 1
    What if a user hold presses the back button and picks a different item in the history? What if they press Forward? – Merc Jun 28 '19 at 08:06

0 Answers0