Search code examples
javascriptjqueryasp.netajaxonbeforeunload

Javascript to detect and send a message to server if the window is closed


I want to know what the answer was for Window Close Confirmation to send a message to server regarding to window close!

I found this, but this doesn't return the user answer.

window.onbeforeunload = function (evt) {
    var message = 'Are you sure?';
    if (typeof evt == 'undefined') {
        evt = window.event;
    }
    if (evt) {
        evt.returnValue = message;
        }
    return message;
};

Solution

  • Solved :)

    window.onunload = window.onbeforeunload = function (evt) {
        var message = 'Are you sure?';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            if (evt.type == "unload" && evt.returnValue) {
    
                // ACTION WHICH SHOULD BE DONE ON CLOSE
    
            }
            evt.returnValue = message;
        }
        return message;
    };