javascriptjquery

How can I detect back navigation on the client in javascript?


Please Note: I am not trying to detect that the back button was clicked. I don't care about that.

I just want to know that they page was loaded on a back navigation. I want to display a warning to my user in one place of my application if they click the back button advising them to refresh.

Edits:

1) I do want my pages to cache. We live in a mobile world now. Not caching is a bad practice.

2) I would like this feature to be URL agnostic. Decoupling is good practice.


Solution

  • <script>
    if (history.state !== null  &&  +history.state < history.length)
    {
        alert("refresh needed");
        history.replaceState(null, "", window.location.href);
    }
    else
    {
        history.replaceState(history.length, "", window.location.href);
    }
    </script>
    

    The first time the page loads, this stores the current length of the history (which is also the page's position in the history) into the history itself, without changing the browser's location or otherwise modifying the history. On a revisit, it checks whether that position is at the end of the history - if not, there's been some back-navigation. It then alerts and clears the stored position.

    Pros:

    Cons: