Browsers Back Button Click With Confirm Box
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 i
Solution 1:
/* 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);
}
});
Solution 2:
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 URLaddEventListener('popstate', function() {
var stayOnPage = confirm("Would you like to save this draft?");
if (!stayOnPage) {
history.back()
} else {
history.pushState(null, null, null);
}
});
});
}
Solution 3:
window.onbeforeunload = function() {
return"Leaving this page will reset the wizard";
};
This would help you.
Solution 4:
The solution by Robert Moore caused duplicate events when refreshing the page for me. Presumably since the state would be re-added multiple times.
I worked around it by only adding state if it is null. I also clean up the listener before going back.
window.onload = function () {
if (window.history && history.pushState) {
if (document.location.pathname === "/MyBackSensitivePath") {
if (history.state == null) {
history.pushState({'status': 'ongoing'}, null, null);
}
window.onpopstate = function(event) {
const endProgress = confirm("This will end your progress, are you sure you want to go back?");
if (endProgress) {
window.onpopstate = null;
history.back();
} else {
history.pushState(null, null, null);
}
};
}
}
};
MDN has a good read on managing state: https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
Solution 5:
It's possible to always display a confirmation box, when a user tries to leave the page. That also includes pressing the back button. Maybe that's a suitable quick-fix for your issue?
window.addEventListener('beforeunload', function() {
return'You really want to go ahead?';
});
Post a Comment for "Browsers Back Button Click With Confirm Box"