防止在刷新/F5中发生OnBeforeUnload()事件 [英] prevent OnBeforeUnload() event from happening in refresh/F5

查看:143
本文介绍了防止在刷新/F5中发生OnBeforeUnload()事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用onbeforeunload事件在关闭页面期间执行操作.
我不希望事件在Refresh/ F5 的情况下发生.

有没有办法做到这一点?

解决方案

不幸的是,onbeforeunload事件在浏览器中侦听页面状态.转到另一个页面以及刷新将更改页面状态,这意味着onbeforeunload仍将被触发.

所以我认为不可能只捕捉刷新.

但是,如果您通过JavaScript监听并阻止Keypress,则可以实现.

可以通过 F5 Ctrl R 键进行刷新,因此您的目标是防止这些操作.

使用jQuery .keydown(),您可以检测到以下键代码:

对于 Ctrl R

$(document).keydown(function (e) {
    if (e.keyCode == 65 && e.ctrlKey) {
        e.preventDefault();
    }
});


对于 F5

$(document).keydown(function (e) {
    if (e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
});

I'm using onbeforeunload event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh / F5.

Is there a way or other event to do this?

解决方案

Unfortunately onbeforeunload event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload will be triggered anyway.

So I think it is not possible to catch only refresh.

But, if you'll listen and prevent Keypress via JavaScript, then it can be achieved.

Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.

using jQuery .keydown() you can detect these keycodes:

For CtrlR

$(document).keydown(function (e) {
    if (e.keyCode == 65 && e.ctrlKey) {
        e.preventDefault();
    }
});


For F5

$(document).keydown(function (e) {
    if (e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
});

这篇关于防止在刷新/F5中发生OnBeforeUnload()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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