Search code examples
javascripthtml

Why is onbeforeunload always showing a dialog


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?


Solution

  • 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