Close window event detection in Firefox

I know this is a very asked question, but believe me, I can’t find an answer via the Internet.

My goal is to bring up a message box only if the user presses the close button (X). The user continues to receive a message box if he presses the back / forward button, and also if he uses F5, CTRL + R, ...

I do not want to associate any other actions, except for the button to close the window, as behind, there will be a session with Ajax. Thus, it is unacceptable to kill a session if the user enters the F5 button.

Here is my code. For information, I know that there is a way in IE to check the clientY object object, but this does not work in Firefox.

$("a").click(function () {
window.onbeforeunload = null;
});

window.onbeforeunload = function (e) {
var closewindowmessage="If you leave this page, your session will be definitely closed.";

  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = closewindowmessage;
  }

  // For Safari
  return closewindowmessage;
};
+3
source share
1 answer

, / . , "", HTML, http://www.example.com/page#something=something. , , "/", .

, , . , , - , , , /, . - , , , - . , , , - "". , Mac . . .

( /), , .

, - . , , , . , F5 Apple + R (Mac). , .

; Firefox Mac. , , , Apple + R, R, , keydown Apple - R. , - , Apple + L, R. , , R.

<script>
// Create an empty array.
window.keys = [];

// Log every key press
window.onkeydown = function (e) {
  var evt = window.event || e;

  var keyCode = e.keyCode || e.which;

  window.keys.push(keyCode)

}

function analyzeKeyPresses(){
  keys.reverse();   // Reverse the array so it easier to handle.
  var doBlock = true;

  // Here we only apply certain checks if there are enough keys in the array. Don't want a JS error...
  switch(window.keys.length){
    case 0:
      doBlock = true;  // Redundant. If there are no key presses logged, assume we should prompt the user.
      break;
    default: // Two or more key presses logged.
      if(keys[0] == 82 && keys[1] == 224) doBlock = false;  // User pressed apple+r on a Mac - don't prompt!
      if(keys[0] == 82 && keys[1] == 17)  doBlock = false;  // User pressed ctrl+r on Windovs (untested) - don't prompt!

      // Note: No break! Intentional fall-through! We still want to check for F5!
    case 1:  // One or more key presses logged.
      if(keys[0] == 116) doBlock = false;   // User pressed F5 - don't prompt!
  }

  keys.reverse();   // Un-reverse the array in case we need to use it again. (Easier to read...)
  return doBlock;
}

window.onbeforeunload = function (e) {
  var closewindowmessage=window.keys.join(" ");

  var blockUnload = analyzeKeyPresses();

  if(blockUnload){
    e = e || window.event;
    // For IE and Firefox
    if (e) {
      e.returnValue = closewindowmessage;
    }

    // For Safari
    return closewindowmessage;
  }
};

</script>
<a href="#1">1</a> <a href="#2">2</a> 
+1

All Articles