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.
/* 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);
}
});
Try this: it's simple and you get total control over the back button.
if (window.history && history.pushState) {
addEventListener('load', function() {
history.pushState(null, null, null); // creates new history entry with same URL
addEventListener('popstate', function() {
var stayOnPage = confirm("Would you like to save this draft?");
if (!stayOnPage) {
history.back()
} else {
history.pushState(null, null, null);
}
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With