使用JavaScript禁用F5和浏览器刷新 [英] Disable F5 and browser refresh using JavaScript

查看:842
本文介绍了使用JavaScript禁用F5和浏览器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript禁用浏览器刷新。

I want to disable browser refreshing using JavaScript.

目前,我正在使用 window.onbeforeunload 和我用户刷新浏览器时不希望它被调用。

Currently, I am using window.onbeforeunload and I don't want it to be called when user refreshes the browser.

最好的方法是什么?

推荐答案

更新最近的评论声称这在新的Chrome中不起作用...如jsFiddle所示,并在我的个人网站上进行了测试,方法仍然适用于Chrome ver 26.0.1410.64 m

Update A recent comment claims this doesn't work in the new Chrome ... As shown in jsFiddle, and tested on my personal site, this method still works as of Chrome ver 26.0.1410.64 m

顺便说一句,这在jQuery中非常容易:

This is REALLY easy in jQuery by the way:

jsFiddle

// slight update to account for browsers not supporting e.which
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5
    /* jQuery < 1.7 */
$(document).unbind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).off("keydown", disableF5);

在旁注:
这只会禁用键盘上的f5按钮。
要真正禁用刷新,必须使用服务器端脚本来检查页面状态更改。
不能说我真的知道怎么做,因为我还没有这样做。

On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes. Can't say I really know how to do this as I haven't done it yet.

在我工作的软件网站上,我们使用我的disableF5函数与Codeigniter的会话数据一起使用。例如,有一个锁定按钮,它将锁定屏幕并提示密码对话框。功能disableF5快速简便,并使该按钮不做任何事情。但是,为了防止鼠标单击刷新按钮,会发生一些事情。

On the software site that I work at, we use my disableF5 function in conjunction with Codeigniter's session data. For instance, there is a lock button which will lock the screen and prompt a password dialog. The function "disableF5" is quick and easy and keeps that button from doing anything. However, to prevent the mouse-click on refresh button, a couple things take place.


  1. 当点击锁定时,用户会话数据有一个名为已锁定的变量,该变量变为TRUE

  2. 当单击刷新按钮时,在主页面上加载方法是对锁定的会话数据进行检查,如果为TRUE,那么我们就是简单地不允许重定向并且页面永远不会改变,无论请求的目的地如何






提示: 尝试使用服务器设置cookie,例如PHP的 $ _ SESSION ,甚至.Net的 Response.Cookies ,以维持where您的客户在您的网站上。这是我用CI的Session类做的更多 Vanilla 方法。最大的区别是CI在您的数据库中使用表,而这些 vanilla 方法在客户端中存储可编辑的cookie。不利的一面是,用户可以清除其cookie。


TIP: Try using a server-set cookie, such as PHP's $_SESSION, or even .Net's Response.Cookies, to maintain "where" your client is in your site. This is the more Vanilla way to do what I do with CI's Session class. The big difference being that CI uses a Table in your DB, whereas these vanilla methods store an editable cookie in the client. The downside though, is a user can clear its cookies.

这篇关于使用JavaScript禁用F5和浏览器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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