【问题标题】:beforeunload event for cookie delete and page refresh用于 cookie 删除和页面刷新的 beforeunload 事件
【发布时间】:2014-07-21 14:28:26
【问题描述】:

在我的网页中,我想在用户关闭窗口时注销用户。为了捕获这个事件,我使用了 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

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

【问题讨论】:

  • 首先,更新到这十年的 jQuery 版本。其次,是什么让您认为您实际上可以阻止用户离开您的页面,而是重新加载页面?

标签: javascript jquery onbeforeunload


【解决方案1】:

问题在于live() 函数,它与JQuery 1.7 Depricated 不同,即使您使用的是旧版本的 jquery,也可能是您的浏览器是最新的浏览器之一,它不允许执行脚本并且可能会抛出 js错误(与我的 Chrome 35.0.1916.153 相同)。

您只需将live() 替换为on()。下面是一些代码sn-p。

$(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;
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多