First, you need to take into account the browser back or fore click event. that event call popstate
The popstate event is fired each time when the current history entry changes (user navigates to a new state). That happens when user clicks on browser's Back/Forward buttons or when history.back()
, history.forward()
, history.go()
methods are programatically called.
in Javascript
window.addEventListener('popstate', function(event) var r = confirm("You pressed a Back button! Are you sure?!");
window.addEventListener('popstate', function(event) {
// The popstate event is fired each time when the current history entry changes.
if (r == true) {
// Call Back button programmatically as per user confirmation.
history.back();
// Uncomment below line to redirect to the previous page instead.
// window.location = document.referrer // Note: IE11 is not supporting this.
} else {
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}
history.pushState(null, null, window.location.pathname);
}, false);