在window.onbeforeunload事件中使用window.event.keyCode在javascript中捕获f5按键事件总是0而不是116

IT技术 javascript jquery
2021-03-02 11:16:29

我正在创建一个 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>

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

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

请注意,以上部分代码在 .cshtml 文件中。

谁能告诉我哪里错了?

6个回答

如果你想让它在 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");
        }
 }

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

但如果您只是想知道用户是否退出页面,您可以简单地使用window.onbeforeunloadhttps : //developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

meo:感谢您的回答,它帮助我进行了一些修改。:)
2021-04-23 11:16:29
不要使用 (e.keyCode == 116) 来检查 F5 ;而不是使用这个
2021-05-06 11:16:29
if (e.code == 'F5') { // 你的代码在这里 }
2021-05-07 11:16:29
我在 Oracle ADF 中使用了这个修改。谢谢。
2021-05-09 11:16:29
当我使用 Firefox 浏览器访问jsfiddle.net/FSrgV/1/embedded/result并按下 F5 时,我看不到任何警报或其他内容......
2021-05-18 11:16:29

不要使用e.keyCode == 116usee.keyCode == '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");
        }
    }

这是因为“t”和“F5”都使用键码编号 116。如果您单独使用键码,那么如果用户按下“t”键,您的页面将刷新。

这绝对不是这种情况。F5 是 116。T 是 84。
2021-05-12 11:16:29
@Adowrath 在某些浏览器和系统上,F5 和 'T' 100% 返回 116 作为键码。
2021-05-15 11:16:29

你可以这样写:

$(document.body).on("keydown", this, function (event) {
    if (event.keyCode == 116) {
        alert('F5 pressed!');
    }
});
document.onkeydown = disableF5;
document.onkeypress = disableF5
document.onkeyup = disableF5;    
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };

修改后的版本并在按 't' 后也可以工作。

按键 116 在 84 之后自动按下

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");

    }else {
        alert("Window closed");
    }
    wasPressed = true;
}