如何在tab关闭上删除jquery cookie

Ban*_*yar 6 javascript cookies jquery

我的cookie工作正常,我没有提及日期,所以当浏览器窗口关闭时,cookie被删除.

但当我关闭浏览器窗口中的选项卡时,cookie不会被删除,并在我打开网站时打开相同的保留cookie状态页面

如何在用户关闭"浏览器"选项卡时删除cookie?

以下是我的代码

$(document).ready(function(){
var href = $.cookie("activeElementHref");
if(href!==null)
{
setContainerHtml(href);
};

$('nav ul li a').click(function(e){
    e.preventDefault();
    href= $(this).attr('href');
    $.cookie("activeElementHref", href) 
    setContainerHtml(href);
});

}); 
$(window).unload(function() {
$.cookies("activeElementHref",null);
});

function setContainerHtml(href) {
        $.ajax({
        type: "POST",
        url: "baker.php",
        data:{send_txt: href},
        success: function(data){
            $('#aside-right, #intro').css('display','none');
            $('#main-content').fadeOut('10', function (){
            $('#main-content').css('width','700px');
            $('#main-content').css('margin','-30px 0 0 100px');
            $('#main-content').html(data);
            $('#main-content').fadeIn('8000');
            });
        }   
    });
}
Run Code Online (Sandbox Code Playgroud)

Yor*_*rgo 6

您必须删除.unload事件上的cookie

$(window).unload(function() {
   $.cookies.del('myCookie');
});
Run Code Online (Sandbox Code Playgroud)

  • 卸载事件甚至删除了我已设置cookie的页面刷新上的cookie (2认同)

per*_*ent 6

前面的答案假设您的 cookie 没有被标记为 http-only。如果你想防止 XSS 攻击,你可能应该将你的 cookie 设置为 http-only,并且通过 javascript 更改 cookie 将不起作用。

解决方案是从服务器中删除 cookie,这将需要一个 HTTP 请求才能关闭选项卡。

大多数 JS 库都会使用异步 HTTP 请求,这会导致选项卡在从服务器接收到过期 cookie 之前关闭,因此异步调用将无法可靠地工作。

我能够让它可靠地工作(至少在 Chrome 上)的唯一方法是进行同步调用:

window.onbeforeunload = function () {

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "api/logout", false);
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)

只需确保您的服务器中的 Logout 端点保持简单,以便快速响应并且 UI 不会被阻塞太长时间。

编辑:如前所述,仅当它是单页应用程序时才应使用 onbeforeunload 来终止 cookie。