用于cookie删除和页面刷新的Beforeunload事件

beforeunload event for cookie delete and page refresh

本文关键字:刷新 Beforeunload 事件 cookie 删除 用于      更新时间:2023-09-26

在我的网页中,我想在用户关闭窗口时注销用户。要捕获此事件,我使用beforeunload事件处理程序。但是当我关闭标签时,removeCookie没有被调用。

下面是示例代码。这是这个SO问题的修改代码

var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
$('a').live('click', function () {
    preventUnloadPrompt = true;
});
$('form').live('submit', function () {
    preventUnloadPrompt = true;
});
if ($("#refreshFlag").val() == 1) {
    preventUnloadPrompt = true;
};
$(window).bind("beforeunload", function (e) {
    var rval;
    if ($("#refreshFlag").val() == 1) {
        preventUnloadPrompt = true;
    };
    if (preventUnloadPrompt) {
        return;
    } else {
        removeCookie();
        window.location = "/";
    }
    return rval;
})

我使用JQuery 1.5.2.

我想要的是当用户刷新页面时,它应该刷新,当选项卡关闭时"removeCookie"应该叫。我在上面的代码中做错了什么?

UPDATE

当刷新出现问题时,此事件从项目中删除。

问题是与live()功能,这是从JQuery 1.7 deprecicate,即使你是使用旧版本的JQuery,可能是你的浏览器是最新的一个,这是不允许脚本执行,可能抛出js错误(与我的Chrome 35.0.1916.153相同)。

您所需要做的就是将live()替换为on()。下面是一些代码片段:

$(document).ready(function(){ debugger;
    var preventUnloadPrompt;
    var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
    $('a').on('click', function(){ preventUnloadPrompt = true; });
    $('form').on('submit', function(){ preventUnloadPrompt = true; });
    if ($("#refreshFlag").val() == 1) { preventUnloadPrompt = true; };
    $(window).on('beforeunload', function() { debugger;
        var rval;
        if ($("#refreshFlag").val() == 1) { preventUnloadPrompt = true; };
        if(preventUnloadPrompt) {
            return;
        } else {
            removeCookie();
            window.location = "/";
        }
        return rval;
    });
});