如何使用 JavaScript 删除所有 cookie? [英] How can I delete all cookies with JavaScript?

查看:23
本文介绍了如何使用 JavaScript 删除所有 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了用 JavaScript 保存 cookie 的代码.现在我需要清除 cookie,而不考虑我分配的值.

I have written code to save cookies in JavaScript. Now I need to clear the cookies irrespective of values that I assigned.

是否有任何脚本模块可以删除由 Javascript 生成的所有 cookie?

Are there any script modules to delete all cookies that were generated by Javascript?

document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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) {
    createCookie(name,"",-1);
}

我还能如何清除所有 cookie?

How else could I clear all of the cookies?

在网络服务器上测试代码会不会有问题?

Will there will be any problems when I test the code on the webserver?

推荐答案

从表面上看,它看起来不错 - 如果您对从 读取的每个 cookie 调用 eraseCookie()document.cookie,那么你所有的 cookie 都会消失.

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

试试这个:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

所有这些都带有以下警告:

All of this with the following caveat:

  • JavaScript 不能删除具有 HttpOnly 标志集.

这篇关于如何使用 JavaScript 删除所有 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆