使用window.onbeforeunload事件中的window.event.keyCode在javascript中捕获f5 keypress事件始终为0而不是116

ism*_*aig 9 javascript jquery

我正在创建一个MVC应用程序.在关闭应用程序(即窗口/选项卡)时,将会话中的变量设置为null,但在刷新应用程序时却没有.我通过以下代码尝试了它.

<script type="text/javascript">
           window.onbeforeunload = function (e) {
               e = e || window.event;
               if (window.event.keyCode == 116) {
                   alert("f5 pressed");
               }
               else {
                   alert("Window closed");
                   //call my c# code to make my variable null, eg:Session["myVariable"] = null;
               }  
           };
</script>
Run Code Online (Sandbox Code Playgroud)

但是当按下F5时,"window.event.keyCode"始终为0而不是116.因此,即使按F5键,我的变量也变为空,这不是我的要求.

即使应用程序(即网页)关闭,即使它的0(这可能是正确的).

请注意,代码的上述部分位于.cshtml文件中.

谁能说出我错在哪里?

meo*_*meo 22

你必须听到不同的事件,如果你想让它工作crossborwser +你必须每次按下按键事件,而不是负载:

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");
        }
 }
Run Code Online (Sandbox Code Playgroud)

这是一个演示:http://jsfiddle.net/FSrgV/1/embedded/result/

但如果您只是想知道用户是否退出页面,您只需使用window.onbeforeunload:https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload


小智 6

不要使用e.keyCode == 166使用e.code =='F5'代替.

 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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是因为't'和'F5'都使用键码116.如果你单独使用键码,那么如果用户按下't'键,你的页面就会刷新.