Browsers back button click with confirm box
javascript, jquery
Solution
/* Prevent accidental back navigation click */
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
const leavePage = confirm("you want to go ahead ?");
if (leavePage) {
history.back();
} else {
history.pushState(null, document.title, location.href);
}
});
Problem
Need to create the javascript confirm pop up on click of browsers back button. If I click on back button pop up will come up and say "you want to go ahead ?" if click on Yes then it would have redirected to previous page. I have following code it is not working as per the requirement. ``` if(window.history && history.pushState){ // check for history api support window.addEventListener('load', function(){ // create history states history.pushState(-1, null); // back state history.pushState(0, null); // main state history.pushState(1, null); // forward state history.go(-1); // start in main state this.addEventListener('popstate', function(event, state){ // check history state and fire custom events if(state = event.state){ event = document.createEvent('Event'); event.initEvent(state > 0 ? 'next' : 'previous', true, true); this.dispatchEvent(event); var r = confirm("Would you like to save this draft?"); if(r==true) { // Do nothing } else { self.location = document.referrer; } // reset state history.go(-state); } }, false); }, false); } ``` Any help in this would be really appreciable.