Reputation: 1291
I am trying to have my javascript pop a dialog if there is data that hasn't been written yet, but it is always showing the confirmation dialog, even if there is nothing to be written.
I have reduced the problem to this minimal failing case:
window.addEventListener("beforeunload", (e) => {
e.returnValue = null;
return null;
});
With this in my code, the windows always ask for confirmation (both Chrome and Firefox). Changing the null's to undefined's doesn't change anything.
Can someone please lend me a clue?
Upvotes: 2
Views: 3842
Reputation: 607
A confirmation dialog will be displayed if event.returnValue
is set to a non-empty. undefined
and null
aren't empty in Javascript.
You should use a conditional and only set/return something if the conditional is true. In other words:
window.addEventListener("beforeunload", (e) => {
if (dataWaitingToBeSent) {
e.returnValue = null;
return null;
}
});
References: beforeUnload event, null primitive, empty statement
Upvotes: 2
Reputation: 818
Try using return;
in order to avoid triggering the confirmation prompt.
In case if you return '',null,false it may trigger the prompt.
If you want to disable the dialog
window.addEventListener("beforeunload", (e) => {
.....
return;
});
Hope this helps ...!
Working fiddle on jquery: https://jsfiddle.net/KishorVelayutham/wfd2xsxk/10/
return ; will stop prompting the dialog.
Upvotes: 2