Reputation: 31
I want a confirm box to come up before unloading a page, and if the user clicks ok there a function needs to be called before leaving the page and if he clicks on cancel it should stay on the same page.
window.onbeforeunload = function() {
if (!submitFormOkay) {
if (confirm("Are you sure you want to leave?")) {
leavepage();
} else {
submitfromokay = true;
location.reload();
}
}
}
Is there anyway I can make this work using JS?
Upvotes: 3
Views: 572
Reputation: 236022
No, you can't. The only way to somehow accomplish that goal is by returning a String-value from your onbeforeunload
handler. Some browsers (Chrome for instance), will use that String and display it in their default warning message. But other browsers, won't use it and just display a standard message, that gives the user a chance to interrupt the page unload.
// Chrome will use the 'Y U LEAVING' string in its warning message now
window.onbeforeunload = function() {
if(!submitFormOkay) {
return 'Y U LEAVING ?';
}
};
Upvotes: 3