Identify Click on browser close button for pop up message

1.9k Views Asked by At

I am trying to implement the functionality to confirm whether "Leaving the page" whenever the user tries to close the browser. As of now i have implemented,

function closeIt(e) {    
// For IE and Firefox prior to version 4
if (e) {
    e.returnValue = 'Sure?';
}

} window.onbeforeunload = closeIt;

This works fine for closing the browser, but instead works for all the links in the page aswell, as there is condition to identify what is causing the onbeforeunload event. Can anyone help me identify them.

Thanks in advance.

1

There are 1 best solutions below

4
shiv On

Referring to various articles and doing some trial and errors, finally developed this idea which works perfectly for me just the way i wanted it to happen. The logic was quiet simpler it implement as well The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the Close('X') button.

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));


$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));

function ConfirmLeave() {
    return "";
}

//Edit start
var prevKey=""       
    $(document).keydown(function (e) {            
        if (e.key=="F5") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
            window.onbeforeunload = ConfirmLeave;   
        }
        else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
            window.onbeforeunload = ConfirmLeave;
        }
        prevKey = e.key.toUpperCase();
//Edit End

The ConfirmLeave function will give the pop up default message, it case there is any need to customize the message, return the text to be displayed instead of empty string.

Please note that the e.key returns undefined in some versions of chrome, so its better to use e.keyCode for key values and refer to http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes for values