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

时间:2014-07-21 14:28:27

标签: javascript jquery onbeforeunload

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

以下是示例代码。这是此SO Question

的修改代码
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

由于刷新问题,此事件已从项目中删除。

1 个答案:

答案 0 :(得分:0)

问题在于live()函数,它是JQuery 1.7 Depricated的描述,即使您使用的是较旧版本的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;
    });
});
相关问题