0

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.

shiv
  • 669
  • 6
  • 11

1 Answers1

-1

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

shiv
  • 669
  • 6
  • 11
  • What about keyboard shortcuts? e.g. (on windows) `alt+f4` or `ctrl+w` – Yoshi Oct 09 '14 at 10:11
  • well that wont work as the logic states that – shiv Oct 09 '14 at 10:12
  • 1
    Well that's my point ;) Just thought it would be viable to include that in the answer? – Yoshi Oct 09 '14 at 10:13
  • for that i think, we can implement keypress funtion similarly where in we will detect specific values and the window.onbeforeunload = ConfirmLeave; running short of time now, but will try to update it once i am done. Thanks for picking that up.. :) – shiv Oct 09 '14 at 10:17