我正在创建一个MVC应用程序.在关闭应用程序(即窗口/选项卡)时,将会话中的变量设置为null,但在刷新应用程序时却没有.
我通过以下代码尝试了它. @H_301_2@<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>
我通过以下代码尝试了它. @H_301_2@<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(这可能是正确的).
任何人都可以告诉我哪里错了吗?
你必须听取不同的事件,如果你想让它工作crossborwser你必须每次按下按键事件,而不是负载:
@H_301_2@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