Handle prompt window closing confirmation
23:29 14 Feb 2021

I know this is a very simple question but even of being a simple question I yet don't find answers to it:

How do I handle if a user confirms to close the page and execute an action in that moment?

Here's the code:

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = '';
    // handle if user confirms to close window
    // if so then call a function (ex, do something)
});

HOW DO I ACHIEVE THIS?

IMPORTANT:

I want to make an API call to alter server side data when the user closes the window, what is more suitable to achieve such goal based on the base question?

javascript html css onbeforeunload