我必须检测用户是否点击了后退按钮.为此,我正在使用
window.onbeforeunload = function (e) {
}
Run Code Online (Sandbox Code Playgroud)
如果用户单击后退按钮,它可以工作.但是,如果用户单击F5或重新加载浏览器按钮,也会触发此事件.我该如何解决?
我想使用JavaScript禁用浏览器刷新.
目前,我正在使用window.onbeforeunload,我不希望在用户刷新浏览器时调用它.
最好的方法是什么?
我正在创建一个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文件中.
谁能说出我错在哪里?