通过 JavaScript 删除 cookie

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

Delete cookies via JavaScript

javascriptcookies

提问by Luis

Possible Duplicate:
Javascript cookie delete

可能重复:
Javascript cookie 删除

Please let me know how to delete specific cookie (I have the name of the cookie its enough..).

请让我知道如何删除特定的 cookie(我有 cookie 的名称就足够了..)。

I really dont have an idea (I dont know JS well...) and when I searched in Google I didn't find a good solution.

我真的没有想法(我不太了解 JS...),当我在 Google 中搜索时,我没有找到一个好的解决方案。

Thank you.

谢谢你。

EDIT:If I can't delete the cookie - let me know how to change the value to "" (empty..), its ok too.

编辑:如果我无法删除 cookie - 让我知道如何将值更改为“”(空..),也可以。

回答by Oded

Stolen from here:

这里被盗:

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

This sets the cookie value to nothing (name + '=;) and sets the expiration time to the past (expiring it immediately).

name + '=;会将cookie 值设置为空 ( ) 并将过期时间设置为过去(立即过期)。

回答by Tim S. Van Haren

Try this (adapted from here):

试试这个(改编自这里):

function DeleteCookie(name, path, domain) 
{
    path = (path ? ";path=" + path : "");
    domain = (domain ? ";domain=" + domain : "");
    var expiration = "Thu, 01-Jan-1970 00:00:01 GMT";

    document.cookie = name + "=" + path + domain + ";expires=" + expiration;
}

Essentially, you delete cookies by setting their expiration date to a date guaranteed to be in the past.

本质上,您可以通过将 cookie 的到期日期设置为保证为过去的日期来删除 cookie。