使用 JavaScript 清除所有 Cookie
本文将帮助你使用 JavaScript 清除所有 cookie。
Cookies
允许客户端和服务器通过 HTTP 通信和传输信息。即使在使用无状态协议 HTTP 时,它也允许客户端保留状态信息。
使用 JavaScript 删除当前域的所有 Cookie
当前文档中的 cookie 属性用于更改使用 HTML DOM cookie
属性购买的 cookie 的属性。document.cookie
返回与当前文档关联的所有以分号分隔的 cookie 的字符串。
语法:
document.cookie = 'key=value';
下面的代码显示了如何使用 JavaScript 删除 cookie。该代码在在线编辑器上运行,以证明该代码只能删除你网站生成的 cookie。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
</title>
</head>
<body>
<main>
<script type="text/javascript">
document.cookie = "username=shiv";
document.cookie = "CONSENT=YES+IN.en+20170903-09-0";
function displayCookies() {
var displayCookies = document.getElementById("display");
displayCookies.innerHTML = document.cookie;
}
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
</script>
<button onclick="displayCookies()">Display Cookies</button>
<button onclick="deleteAllCookies()">Delete Cookies</button>
<p id="display"></p>
</main>
</body>
</html>
上面的代码有两个限制。
- 设置了
HttpOnly
标志的 Cookie 不会被删除,因为HttpOnly
标志会禁用 JavaScript 对 cookie 的访问。 - 设置为路径值的 Cookie 不会被删除。 (虽然这些 cookie 出现在
Deleted
下,但如果不为安装路径指定相同的值,则无法删除它们。)
输出:
当你点击显示 Cookie
时,它将显示 cookie。
你还可以在检查器中查看 cookie。
点击 Delete Cookies
后,它会删除它,你必须再次点击显示 cookies,看看它是否被删除。
你还可以在检查器中查看它是否被删除。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。