Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 567
Jordan Avatar asked Mar 18 '15 15:03

Jordan


People also ask

How do I know if my back button is pressed?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.

How do I check stack history?

history object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the back() , forward() , and go() methods. The history. length returns the number of URLs in the history stack.


2 Answers

<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:

  • Does not trigger alert on refresh.

  • Does not trigger alert if page is visited again later, either in the same tab or a different one.

Cons:

  • Cannot distinguish between forward-navigation and back-navigation. I.e., if the user goes back further than this page and then navigates forward to it, it will still alert, because some back-navigation was used to get here. However, I would think that even in this situation, you would want the user to refresh.

  • Only alerts once. If the user then goes forward and back again, it won't alert again. Since the user has already been notified, perhaps this is not important.

like image 96
radiaph Avatar answered Nov 13 '22 04:11

radiaph


Here is a simple method. It will detect the page was loaded from both back and forward navigation though.

if(window.performance.navigation.type === 2) {
   // the page was navigated to via the forward or back button
   // refresh
}

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

like image 23
Ryan Breece Avatar answered Nov 13 '22 04:11

Ryan Breece