0

I'm using the following JavaScript to prevent user to go back after logout.

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function() {
    history.pushState(null, null, document.URL);
});

The above code is placed both in <head></head> section and at the bottom of the page. But still users are able to go back. Any idea?

Wing
  • 8,438
  • 4
  • 37
  • 46
s.k.paul
  • 7,099
  • 28
  • 93
  • 168
  • 2
    From [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event#when_popstate_is_sent): "browsers may not fire the popstate event at all unless the page has been interacted with". If the user doesn't interact with your page before using the back button, the event will not fire. – Henry Aug 17 '23 at 11:49
  • Does this answer your question? [How can I stop the browser back button using JavaScript?](https://stackoverflow.com/questions/12381563/how-can-i-stop-the-browser-back-button-using-javascript) – David Aug 17 '23 at 11:52
  • As I found out today: `bfcache` takes precedence over `popstate`. See: https://web.dev/bfcache/ – freedomn-m Aug 17 '23 at 12:00
  • 1
    TBH I can't see how your code would *prevent* someone from going back, or at least stop them from right-clicking the back button and selecting your page from the history. – freedomn-m Aug 17 '23 at 12:01
  • You could have an in-between page after logout that forwards you to the homepage, for example. Going back will then only send them to the URL that forwards them again. You could still navigate back more using the browser history but you wouldn't accidentally go back. – Peter Krebs Aug 17 '23 at 12:53

1 Answers1

1

you don't need to return back u should restrict the page by server-side code(PHP, java, python,...) to prevent the user to get previous data after (logout or session destroy) and redirect the user to the home page

  • unrecommended the following code
history.pushState(null, null, location.href);
window.onpopstate = function (event) {
    history.go(1);
}; 

remove code javascript from the head tag it must be placed in the body tag