Javascript 如何删除cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2144386/
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-22 22:56:27  来源:igfitidea点击:

How to delete a cookie?

javascriptcookies

提问by kennedy

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?

我创建cookie的功能是否正确?如何删除程序开始时的 cookie?有简单的编码吗?

function createCookie(name,value,days)
function setCookie(c_name,value,1) {
  document.cookie = c_name + "=" +escape(value);
}

setCookie('cookie_name',mac);

function eraseCookie(c_name) {
  createCookie(cookie_name,"",-1);
}

回答by ACP

Try this:

尝试这个:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

Or:

或者:

function delete_cookie( name ) {
  document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

回答by Luca Matteis

Here a good link on Quirksmode.

这里有一个关于Quirksmode的好链接。

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

回答by Collin Anderson

would this work?

这行得通吗?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Agecauses the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

我知道Max-Age在创建 cookie 时会导致 cookie 成为 IE 中的会话 cookie。不确定删除 cookie 时它是如何工作的。

回答by Vitalii Fedorenko

Here is an implementation of a delete cookiefunction with unicode support from Mozilla:

这是Mozilla 支持 unicode的删除 cookie函数的实现:

function removeItem(sKey, sPath, sDomain) {
    document.cookie = encodeURIComponent(sKey) + 
                  "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + 
                  (sDomain ? "; domain=" + sDomain : "") + 
                  (sPath ? "; path=" + sPath : "");
}

removeItem("cookieName");

If you use AngularJs, try $cookies.remove(underneath it uses a similar approach):

如果您使用 AngularJs,请尝试$cookies.remove(在它下面使用类似的方法):

$cookies.remove('cookieName');

回答by Markus Nordhaus

You can do this by setting the date of expiry to yesterday.

您可以通过将到期日期设置为昨天来做到这一点。

Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.

将其设置为“-1”不起作用。这将 cookie 标记为 Sessioncookie。

回答by Luca Borrione

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

要删除 cookie,我再次将其设置为空值并在 1 秒后过期。具体来说,我总是使用以下其中一种口味(我更喜欢第二种):

1.

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

用法:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

用法:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");

回答by Lemmings19

Some of the other solutions might not work if you created the cookie manually.

如果您手动创建 cookie,其他一些解决方案可能不起作用。

Here's a quick way to delete a cookie:

以下是删除 cookie 的快速方法:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;

回答by John

I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:

我在删除通过 JavaScript 制作的 cookie 时遇到了麻烦,在我添加了主机后它可以工作(将下面的代码滚动到右侧以查看location.host)。清除域上的 cookie 后,请尝试以下操作以查看结果:

if (document.cookie.length==0)
{
 document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;

 if (document.cookie.length==0) {alert('Cookies disabled');}
 else
 {
  document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;

  if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
  else {alert('document.cookies.length = '+document.cookies.length);}
 }
}