使用window.onbeforeunload事件中的window.event.keyCode在javascript中捕获f5 keypress事件始终为0而不是116 [英] capturing f5 keypress event in javascript using window.event.keyCode in window.onbeforeunload event is always 0 and not 116

查看:267
本文介绍了使用window.onbeforeunload事件中的window.event.keyCode在javascript中捕获f5 keypress事件始终为0而不是116的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 the application. I tried it through the following code.

<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键也变为空,这不是我的要求。

But when F5 is pressed then, "window.event.keyCode" is always 0 and not 116. Because of which my variable is becoming null even upon F5 key press which is not my requirement.

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

Even when the application (i.e. webpage) is closed,even then its 0 (which is probably correct).

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

Please note that the above part of the code is in .cshtml file.

任何人都可以告诉我哪里错了吗?

Can anyone tell where am i wrong ?

推荐答案

如果你想要这个,你必须听不同的事件工作crossborwser +每次按下时都要听按键事件,而不是加载:

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

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

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

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

这篇关于使用window.onbeforeunload事件中的window.event.keyCode在javascript中捕获f5 keypress事件始终为0而不是116的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆