capturing f5 keypress event in javascript using window.event.keyCode in window.onbeforeunload event is always 0 and not 116

You have to listen to different events if you want this to work crossborwser + you have to listen to the key-event every time its pressed, not on load:

document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;

var wasPressed = false;

function fkey(e){
        e = e || window.event;
       if( wasPressed ) return; 

        if (e.keyCode == 116) {
             alert("f5 pressed");
            wasPressed = true;
        }else {
            alert("Window closed");
        }
 }

here is a demo: http://jsfiddle.net/FSrgV/1/embedded/result/

but if you simply want to know if the user quits the page you could simply use window.onbeforeunload: https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload


Dont use e.keyCode == 166 use e.code == 'F5' instead.

 function fkey(e){
    e = e || window.event;
   if( wasPressed ) return; 

    function fkey(e){
        e = e || window.event;
        if (e.code === 'F5') {
            alert("f5 pressed");
            wasPressed = true;
        }else {
            alert("Window closed");
        }
    }

This is because the 't' and 'F5' both use the keycode number 116. If you go on keycode alone then if the user presses the 't' key your page will refresh.


You could just write it like this:

$(document.body).on("keydown", this, function (event) {
    if (event.keyCode == 116) {
        alert('F5 pressed!');
    }
});