jQuery 如何在浏览器关闭时删除jquery中的cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8323346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:21:35  来源:igfitidea点击:

how to delete cookie in jquery at the time of browser closing?

jquerycookies

提问by Priyanka

I have created a cookie by using jQuery. I want to delete the cookie with jQuery when the browser closes. How do I do this?

我使用 jQuery 创建了一个 cookie。我想在浏览器关闭时用 jQuery 删除 cookie。我该怎么做呢?

I've written the following script:

我编写了以下脚本:

$(function () {
         if ($.cookie('toggle') == "toggle") {
             $('#toggleText').show();
             $('#displayText').text("Less");
         }
         else {
             $('#toggleText').hide();
             $('#displayText').text("More");
         }
         $('#displayText').click(function () {
             if ($(this).text() == "More") {
                 $('#toggleText').show();
                 $(this).text("Less");
                 $.cookie('toggle', 'toggle');

             } else {
                 $('#toggleText').hide();
                 $(this).text("More");
                 $.cookie('toggle', 'nottoggle');

             }
         });

     })

The cookie should also not be deleted when the user refreshes the browser.

用户刷新浏览器时也不应删除 cookie。

Thanks.

谢谢。

回答by Manse

What you are talking about is a transient cookie - cookies are transient (they are removed when the browser is closed) when you set a cookie with no expiry date. They exist for the current browser session only

您正在谈论的是临时 cookie - 当您设置没有到期日期的 cookie 时,cookie 是临时的(它们会在浏览器关闭时被删除)。它们仅存在于当前浏览器会话中

If you are using this implementation -> http://code.google.com/p/cookies/wiki/Documentation

如果您使用此实现 -> http://code.google.com/p/cookies/wiki/Documentation

They provide a delete method :

他们提供了一个删除方法:

$.cookies.del('myCookie');
//deletes a cookie, 'myCookie', with default options

Or removing a cookie using pure JavaScript :

或者使用纯 JavaScript 删除 cookie:

document.cookie = "myCookie=; expires=Thu, 01-Jan-70 00:00:01 GMT;";

document.cookie = "myCookie=; expires=Thu, 01-Jan-70 00:00:01 GMT;";

There is an unloadevent that you can bind to that will allow you to remove the cookies when the browser closes -

unload您可以绑定一个事件,该事件将允许您在浏览器关闭时删除 cookie -

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

当用户离开页面时, unload 事件被发送到 window 元素。这可能意味着许多事情之一。用户可以点击链接离开页面,或者在地址栏中输入新的 URL。前进和后退按钮将触发事件。关闭浏览器窗口将导致事件被触发。即使页面重新加载也会首先创建一个卸载事件。

Example :

例子 :

$(window).unload(function() {
 // delete your cookie here
});

Update ....

更新 ....

It seems that using session cookies with the jQuery plugin isnt as simple as it should be ... i think that using a plugin for such a simple task is a waste of bandwidth (I know its only a couple of KB - but thing of the poor mobile users) .. these are the 2 methods I alwaysuse for getting / setting cookies :

似乎在 jQuery 插件中使用会话 cookie 并不像它应该的那么简单......我认为使用插件来完成这样一个简单的任务是浪费带宽(我知道它只有几个 KB - 但最重要的是可怜的移动用户).. 这些是我一直用于获取/设置 cookie的两种方法:

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}


function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

And using these methods is very simple ....

并且使用这些方法非常简单......

setCookie('myCookie','myvalues',5); 
// the 5 is the number of days in the future the cookies should be removed
// leave this parameter out or set to null for transient cookie

myvalues = getCookie('myCookie');

Another Update ....

另一个更新....

Its not that difficult with the jQuery plugin, you just need to set some options :

使用 jQuery 插件并不难,您只需要设置一些选项:

var newOptions = {
  expiresAt: null
};
$.cookies.setOptions(newOptions);
or 
$.cookies.setOptions({expiresAt: null});

回答by Emre Erkan

If you want delete cookie when you close browser than you should set a session cookie, which automatically expires when browser closed. But if you want delete cookie when you close a tab than you should use window.unloadand window.beforeunloadevents, write a function to delete necessary cookies and attach to these events.

如果您想在关闭浏览器时删除 cookie,那么您应该设置一个会话 cookie,它会在浏览器关闭时自动过期。但是如果你想删除Cookie当您关闭比你应该使用一个标签window.unloadwindow.beforeunload事件,编写一个函数来删除必要的饼干和附加到这些事件。

回答by coolguy

function deleteCookie(name) {
                setCookie(name,"",-1);
            }
            function setCookie(name,value,days) {
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime()+(days*24*60*60*1000));
                    var expires = "; expires="+date.toGMTString();
                }
                else expires = "";
                document.cookie = name+"="+value+expires+"; path=/";
            }
$(window).unload(function() {
 deleteCookie('Your cookie to delete name');
});

回答by Sudhanshu Yadav

use simple javascript code as mentioned above to create or delete cookie. And if you want to make it as a session cookie(which will expire on browser close) dont pass day parameter.

使用上面提到的简单 javascript 代码来创建或删除 cookie。如果您想将其作为会话 cookie(将在浏览器关闭时过期),请不要传递 day 参数。

like

喜欢

setCookie('test','aa');

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}