JavaScript 和 Cookie
本文讲解 JavaScript 和 Cookie。
我们将循序渐进地详细讲解一切,从 Cookie 的基础、读写、安全性到实际范例。
YouTube Video
javascript-cookie.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 1em;
14 padding-bottom: 10em;
15 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16 background-color: #f7f9fc;
17 color: #333;
18 line-height: 1.6;
19 }
20
21 .container {
22 max-width: 800px;
23 margin: 0 auto;
24 padding: 1em;
25 background-color: #ffffff;
26 border: 1px solid #ccc;
27 border-radius: 10px;
28 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
29 }
30
31 .container-flex {
32 display: flex;
33 flex-wrap: wrap;
34 gap: 2em;
35 max-width: 1000px;
36 margin: 0 auto;
37 padding: 1em;
38 background-color: #ffffff;
39 border: 1px solid #ccc;
40 border-radius: 10px;
41 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
42 }
43
44 .left-column, .right-column {
45 flex: 1 1 200px;
46 min-width: 200px;
47 }
48
49 h1, h2 {
50 font-size: 1.2rem;
51 color: #007bff;
52 margin-top: 0.5em;
53 margin-bottom: 0.5em;
54 border-left: 5px solid #007bff;
55 padding-left: 0.6em;
56 background-color: #e9f2ff;
57 }
58
59 button {
60 display: block;
61 margin: 1em auto;
62 padding: 0.75em 1.5em;
63 font-size: 1rem;
64 background-color: #007bff;
65 color: white;
66 border: none;
67 border-radius: 6px;
68 cursor: pointer;
69 transition: background-color 0.3s ease;
70 }
71
72 button:hover {
73 background-color: #0056b3;
74 }
75
76 #output {
77 margin-top: 1em;
78 background-color: #1e1e1e;
79 color: #0f0;
80 padding: 1em;
81 border-radius: 8px;
82 min-height: 200px;
83 font-family: Consolas, monospace;
84 font-size: 0.95rem;
85 overflow-y: auto;
86 white-space: pre-wrap;
87 }
88
89 .highlight {
90 outline: 3px solid #ffc107; /* yellow border */
91 background-color: #fff8e1; /* soft yellow background */
92 transition: background-color 0.3s ease, outline 0.3s ease;
93 }
94
95 .active {
96 background-color: #28a745; /* green background */
97 color: #fff;
98 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
99 transition: background-color 0.3s ease, box-shadow 0.3s ease;
100 }
101 </style>
102</head>
103<body>
104 <div class="container">
105 <h1>JavaScript Console</h1>
106 <button id="executeBtn">Execute</button>
107 <div id="output"></div>
108 </div>
109
110 <script>
111 // Override console.log to display messages in the #output element
112 (function () {
113 // Override console.log
114 const originalLog = console.log;
115 console.log = function (...args) {
116 originalLog.apply(console, args);
117 const message = document.createElement('div');
118 message.textContent = args.map(String).join(' ');
119 output.appendChild(message);
120 };
121
122 // Override console.error
123 const originalError = console.error;
124 console.error = function (...args) {
125 originalError.apply(console, args);
126 const message = document.createElement('div');
127 message.textContent = args.map(String).join(' ');
128 message.style.color = 'red'; // Color error messages red
129 output.appendChild(message);
130 };
131 })();
132
133 document.getElementById('executeBtn').addEventListener('click', () => {
134 // Prevent multiple loads
135 if (document.getElementById('externalScript')) return;
136
137 const script = document.createElement('script');
138 script.src = 'javascript-cookie.js';
139 script.id = 'externalScript';
140 //script.onload = () => console.log('javascript-cookie.js loaded and executed.');
141 //script.onerror = () => console.log('Failed to load javascript-cookie.js.');
142 document.body.appendChild(script);
143 });
144 </script>
145</body>
146</html>JavaScript 和 Cookie
Cookie 指的是存储在用户浏览器中的小型数据。它们主要用于以下目的:。
- 用户认证(保持登录状态)
- 保存用户设置(语言、主题等)
- 跟踪(浏览历史等)
在 JavaScript 中,可以通过 document.cookie 读取和写入 Cookie。
创建(写入)Cookie
Cookie 使用以下语法创建:。
1document.cookie = "username=JohnDoe";- 这段代码将在浏览器中保存一个名为
"username=JohnDoe"的 Cookie。
创建带有过期日期的 Cookie
Cookie 可以设置过期日期。如果没有设置过期日期,它将被视为会话 Cookie,在浏览器关闭时被删除。
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3const cookieText = "username=JohnDoe; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4document.cookie = cookieText;
5console.log(`Cookie Text : ${cookieText}`);
6console.log(`Cookie Value : ${document.cookie}`);expires属性以 UTC 格式指定 Cookie 的过期日期。path属性指定 Cookie 将被发送的路径。/表示整个站点。- 如果指定了
SameSite=None,即使是跨站请求,也会发送该Cookie。但是,在这种情况下,必须始终包含Secure属性。 - 指定
Secure属性会将该Cookie限制为仅通过 HTTPS 通信,提高安全性。 - 通过引用
document.cookie,你可以以字符串的形式获取当前页面上所有可用的Cookie。 - 通过使用
console.log,你可以检查在浏览器中实际设置的Cookie值与可获取的值之间的差异。
获取(读取)Cookie
你可以通过 document.cookie 以字符串形式获取所有的 Cookie。
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3document.cookie = "theme=dark; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4
5console.log(document.cookie);
6// Output: "username=JohnDoe; theme=dark"
document.cookie的返回值是一个字符串,所有的Cookie按照“key=value;”的格式拼接在一起。- 可以编写函数去解析该字符串并提取所需的值,这样更方便。
用于获取 Cookie 值的函数
1function getCookie(name) {
2 const cookies = document.cookie.split('; ');
3 for (const cookie of cookies) {
4 const [key, value] = cookie.split('=');
5 if (key === name) {
6 return decodeURIComponent(value);
7 }
8 }
9 return null;
10}
11
12console.log(getCookie("username")); // "JohnDoe"
- 该函数通过
split()拆分键和值,并在与指定的键匹配时返回对应的值。 - 通过使用
decodeURIComponent,可以正确获取已编码的字符。 - 如果对应的键不存在,则返回
null。
删除 Cookie
通过将 Cookie 的过期日期设置为过去的时间,可以删除该 Cookie。
1document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=None; Secure";
2
3console.log(document.cookie);
4// Output: "theme=dark"
- 将
username赋值为空并将到期日期设置为过去的时间,该Cookie就会被删除。 - 在删除
Cookie时,必须将path、SameSite和Secure属性与创建该Cookie时所用的属性保持一致。 - 在此示例中,
username被删除,而theme=dark等其他Cookie保留。
Cookie 选项
你可以指定各种选项来控制 Cookie 的行为。主要选项如下:。
-
expires指定 Cookie 的过期日期(UTC 格式)。如果未指定,Cookie 会成为会话 Cookie,并在浏览器关闭时被删除。 -
max-age以秒为单位指定 Cookie 的过期时间。此项优先于expires。 -
path指定 Cookie 被发送的路径。例如,指定/admin后,Cookie 仅会发送给该路径下的页面。 -
domain指定 Cookie 有效的域名。通常设置为当前域名,但也可以适用于所有子域名,如.example.com。 -
secure指定此属性后,Cookie 仅通过 HTTPS 发送。为增强安全性,保存敏感信息时一定要设置该属性。 -
SameSite控制 Cookie 是否用于跨站点请求。可设置以下三种值之一:。-
StrictCookie 仅在同一站点请求时发送。 -
Lax通常导航会发送 Cookie,但存在一些限制。 -
None跨站点请求时也会发送 Cookie。但此时还必须指定Secure属性。
-
示例:安全 Cookie
1document.cookie = "sessionId=abc123; secure; SameSite=Strict";- 如果指定
secure,该Cookie只会通过 HTTPS 通信发送。 - 如果指定
SameSite=Strict,则该Cookie不会在跨站请求时发送,从而可作为 CSRF 的对策。 - 这些安全属性对于用于身份验证或会话管理的重要
Cookie至关重要。
编码与解码
由于 Cookie 的值可能包含特殊字符,建议使用 encodeURIComponent 来确保安全。
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3
4const username = "JohnDoe";
5document.cookie =
6 "username=" + encodeURIComponent(username) +
7 "; max-age=604800; path=/; SameSite=None; Secure";
8
9console.log(decodeURIComponent(getCookie("username"))); // "JohnDoe"
- 通过使用
encodeURIComponent,可以安全地在Cookie中存储空格、符号等内容。 - 读取时,使用
decodeURIComponent将其还原为原始字符串。 - 在此示例中,使用
max-age=604800设置了7天(604,800秒)的过期时间。这是一种指定过期日期的方法,与expires类似。max-age可以以秒为单位指定,通常更易于使用。
实际例子:保存和加载主题
以下是将用户选择的主题保存到 Cookie,并在下次访问时自动应用的示例。
1function setTheme(theme) {
2 document.cookie =
3 "theme=" + encodeURIComponent(theme) +
4 "; max-age=604800; path=/; SameSite=None; Secure"; // 1 week
5 applyTheme(theme);
6}
7
8function applyTheme(theme) {
9 document.body.style.backgroundColor = theme === "dark" ? "#333" : "#fff";
10 document.body.style.color = theme === "dark" ? "#fff" : "#000";
11}
12
13function getCookie(name) {
14 const cookies = document.cookie.split('; ');
15 for (const cookie of cookies) {
16 const [key, value] = cookie.split('=');
17 if (key === name) {
18 return decodeURIComponent(value);
19 }
20 }
21 return null;
22}
23
24const savedTheme = getCookie("theme");
25if (savedTheme) {
26 applyTheme(savedTheme);
27}1<button onclick="setTheme('light')">Light</button>
2<button onclick="setTheme('dark')">Dark</button>setTheme函数将所选主题保存到Cookie,并立即调用applyTheme更新界面。applyTheme函数根据所选主题切换body的背景色和文字颜色。- 在本例中,由于设置了
max-age=604800,主题设置会被保存一周。 - 由于用户的选择可以在再次访问页面时保留,提升了用户体验。
Cookie 的限制与注意事项
使用 Cookie 时请注意以下几点:。
-
大小限制 单个 Cookie 的大小通常被限制在约 4KB。
-
可保存 Cookie 数量的限制 根据不同浏览器,每个域大约只能保存20到50个。
-
安全注意事项
Cookie的内容基本上是以明文保存的,因此不适合存储如密码等机密信息。 -
JavaScript 无法访问的 Cookie 带有
HttpOnly属性的 Cookie 出于安全原因无法通过 JavaScript 读取。
服务器与 Cookie
1Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict有些 Cookie 属性,如 HttpOnly,不能通过 JavaScript 设置。这些属性必须在服务器端设置。
总结
通过 JavaScript 操作 Cookie 可以提升用户体验并保持状态。然而,请牢记以下要点,以便安全且适当地加以处理。
-
仅储存最必要的信息 从隐私和安全的角度,应避免存储个人或敏感信息,只记录必要的数据。
-
正确设置安全属性 设置如
Secure和SameSite等属性,以防止跨站攻击,如 XSS 和 CSRF。 -
数据编码与解码 请使用
encodeURIComponent和decodeURIComponent安全地存储和读取 Cookie 的值,以便正确处理特殊字符和日文。
通过学习正确使用 Cookie,可以构建更高级且安全的 Web 应用程序。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。