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

后端 未结 7 884
南方客
南方客 2020-11-29 09:02

i am creating an MVC application.There was a neccessitity to make a variable in a session to null upon closing of the application (i.e. window/tab) but not upon refreshing t

7条回答
  •  粉色の甜心
    2020-11-29 09:10

    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.

提交回复
热议问题