解决方法
只需指定要删除的Cookie的相同路径,将其过期到期.
document.cookie = 'name=value1; path=/'; document.cookie = 'name=value2; path=/path/'; alert(document.cookie); // name=value1; name=value2 document.cookie = 'name=; path=/path/; expires=' + new Date(0).toUTCString(); alert(document.cookie); // name=value1
将其更改为以/的路径过期的cookie仍然只会过期其中一个cookie – 给定的路径必须匹配路径集:
document.cookie = 'name=; path=/; expires=' + new Date(0).toUTCString(); alert(document.cookie); // name=value2
要删除这两个,您必须使用他们的路径到期:
document.cookie = 'name=; path=/; expires=' + new Date(0).toUTCString(); document.cookie = 'name=; path=/path/; expires=' + new Date(0).toUTCString(); alert(document.cookie); // {blank}
现在,这些例子假设你正在浏览/ path /或者一个子目录.
[编辑]
要大量删除,请尝试这样:
function expireAllCookies(name,paths) { var expires = new Date(0).toUTCString(); // expire null-path cookies as well document.cookie = name + '=; expires=' + expires; for (var i = 0,l = paths.length; i < l; i++) { document.cookie = name + '=; path=' + paths[i] + '; expires=' + expires; } } expireAllCookies('name',['/','/path/']);
您还可以通过拆分和迭代window.location.pathname来伪造路径查找:
function expireActiveCookies(name) { var pathname = location.pathname.replace(/\/$/,''),segments = pathname.split('/'),paths = []; for (var i = 0,l = segments.length,path; i < l; i++) { path = segments.slice(0,i + 1).join('/'); paths.push(path); // as file paths.push(path + '/'); // as directory } expireAllCookies(name,paths); }