Search code examples
javascriptonbeforeunload

How to use onbeforeunload event handler without the pop up message?


I am trying to use onbeforeunload event to log some finalized log of the page (I cannot do it in the middle of the visit, because I have to get the log right before user leaves).

function handleBeforeUnload(evt) {
    evt.preventDefault();
    evt.returnValue = '';

    // make some log
    logSomeFinalizedInfo();

    return null;
}

However, on Android phone, this pops up a message "Are you sure you want to leave", which is not expected, how can I use this event handler without having this message pop up?


Solution

  • Finally found the solution, which is to remove the handler after use (removeEventListener):

    function handleBeforeUnload(evt) {
        evt.preventDefault();
        evt.returnValue = '';
    
        // make some log
        logSomeFinalizedInfo();
    
        removeEventListener('beforeunload', handleBeforeUnload);
    }