how to delete jquery cookie on tab close

会有一股神秘感。 提交于 2021-02-06 11:42:13

问题


My cookie is working fine i m not mentioning date so when the browser window is closed the cookie is deleted.

but when i close a tab in a browser window the cookie is not deleted and open the same preserved cookie state page when i open the website

How to delete a cookie when a user closes a Browser tab ?

Below is my code

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

回答1:


You have to delete the cookie on .unload event

$(window).unload(function() {
   $.cookies.del('myCookie');
});



回答2:


The previous answers assume that your cookies are not marked as http-only. If you want to prevent XSS attacks, you should probably set your cookies as http-only, and changing the cookies via javascript will not work.

The solution is to delete the cookie from the server, which will require an HTTP request before the tab is closed.

Most JS libraries will use asynchronous HTTP requests, which will cause the tab to be closed before receiving the expired cookie from the server, so asynchronous calls will not work reliably.

The only way that I was able to make it work reliably (at least on Chrome) was by making a synchronous call:

window.onbeforeunload = function () {

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

Just make sure to keep your Logout endpoint in your server simple so the response is fast and the UI is not blocked for too long.

Edit: as mentioned before, using onbeforeunload to kill the cookies should only be used if it's a single-page application.




回答3:


you can call delete cookies function on onunload & onbeforeunload events.

the function to delete cookies is here how to delete cookie in jquery at the time of browser closing?



来源:https://stackoverflow.com/questions/9158042/how-to-delete-jquery-cookie-on-tab-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!