如何删除所有使用JavaScript的cookie

如何删除所有使用JavaScript的cookie

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

问题描述

我已经编写了代码来用JavaScript保存Cookie。



有任何脚本模块可以删除由?



我的示例代码:



  document.cookie ='ppkcookie2 =另一个测试; expires = Fri,2001年8月3日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 = /;
}

函数readCookie(name){
var nameEQ = name +=;
var ca = document.cookie.split(';');
for(var i = 0; i var c = ca [i]; $ c $ b 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?

$ b

解决方案

但是,当我在Web服务器上测试代码时,在它的表面上它看起来确定 - 如果你调用你的eraseCookie()每个你从 document.cookie 读取的cookies,那么所有的cookie都会消失。



也许像这样:

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

所有这一切都有caveat:




  • JavaScript无法删除已设置HttpOnly标记的Cookie。


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

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

My Sample Code:

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);
}

How else could I clear all of the cookies?

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

解决方案

But on the face of it it looks OK - if you call your eraseCookie() on each of the cookies that you read from document.cookie, then all the cookies would be gone.

Maybe something like this:

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

All this with caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

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

08-16 08:15