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

Leave a Comment