Javascript 简明教程

JavaScript cookie 属性用于设置 cookie 的附加信息,例如路径、域、到期日期等。在 JavaScript 中,您可以在设置新 cookie 或更新 cookie 时指定 cookie 属性。例如,您可以使用 'expires' 属性设置 cookie 的到期日期。

The JavaScript cookie attributes are used to set additional information about a cookie such as path, domain, expiry date, etc. In JavaScript, you can specify the cookie attributes while setting up a new cookie or updating the cookie. For example, you can set the cookie’s expiry date using the 'expires' attributes.

简单来说,cookie 属性用于控制 cookie 的行为以及在浏览器中如何使用 cookie。

In simple terms, cookie attributes are used to control the behavior of the cookies and how the cookie is used in the browser.

此处,我们在下表中列出了所有 cookie 属性及其说明。

Here, we have listed all cookie attributes in the table below with its description.

Attribute

Description

Default Value

Name/Value

It is used to store the cookies in the browser.

Domain

To specify the domain for whose cookie is valid.

Website of domain. For example, tutorialspoint.com

Path

The path to the directory or web page that sets the cookie.

/ (entire domain)

Expires

It is used to specify the date and time when the cookie should expire.

Current session

Max-Age

It is used to specify the time limit after that cookie should expire.

Current session

Secure

If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

false

HttpOnly

It prevents accessing the cookies via JavaScript to make cookies secure.

false

SameSite

It is used to specify how third-party cookies should be handled.

Lax

Priority

It defines the priority of the cookies.

1000

Site/Service

To get information about the origin site of the cookie.

SourcePort

To get the port of the source for the cookie.

StoragePartition

It defines which storage partition is used to store cookies.

Size

It represents the size of the cookies.

The size depends on the text length.

但是,最重要的是,属性是可选的。

However, above all, attributes are optional.

此外,你无法操作 Cookie 的所有属性。浏览器设置一些属性。

Also, you can’t manipulate all attributes of the cookies. The browser sets some attributes.

Check the Attribute Value in the Browser

你可以将属性设置为 Cookie,但无法访问这些属性。要检查是否设置了该属性,可以使用浏览器控制台。

You can set the attributes to the cookie, but you can’t access the attributes. To check whether the attribute is set, you can use the browser console.

按照以下步骤在浏览器控制台中检查 Cookie。

Follow the steps below to check cookies in the browser console.

Step 1 - 在浏览器中单击鼠标右键。它将打开菜单。你需要选择“检查”选项。它将打开开发者工具。

Step 1 − Right click in the browser. It will open the menu. You need to select the 'inspect' option. It will open the developer tool.

cookie attributes step1

Step 2 - 之后,你需要转到“应用程序/存储”选项卡。

Step 2 − After that, you need to go to the Application/ Storage tab.

cookie attributes step2

Step 3 − 在边栏中,选择“cookies”。

Step 3 − In the sidebar, select 'cookies’.

cookie attributes step3

Step 4 − 现在,单击任何 cookie 以检查它们的名称、值和其他属性值。

Step 4 − Now, click on any cookies to check their name, value, and other attribute values.

cookie attributes step4

上述步骤仅适用于 Chrome 网络浏览器。根据所使用的浏览器,步骤可能有所不同。

The above steps are only for the Chrome web browser. The step can differ according to what browser you are using.

这里,你将逐个学习每个属性及其示例。

Here, you will learn each attribute one by one with examples.

Cookie’s Name/Value Attribute

名称属性用于存储 cookie 数据。它将数据作为值。如果你想在“名称”属性的值中使用特殊字符,则需要使用 encodeURIComponent() 方法对文本进行编码。

The Name attribute is used to store the cookie data. It takes the data as a value. If you want to use the special characters in the value of the 'Name' attribute, you need to encode the text using the encodeURIComponent() method.

Syntax

遵循以下语法设置 cookie 的名称属性。

Follow the syntax below to set the Name attribute of the cookie.

let value = encodeURIComponent(cookieValue);
document.cookie = "name=" + value + ";";

在上述语法中,我们使用 encodeURIComponent() 方法对“cookieValue”进行了编码,并将编码后的值用作名称属性值。

In the above syntax, we have encoded the 'cookieValue' using the encodeURIComponent() method and used the encoded value as a name attribute value.

Example

在下面的代码中,我们设置了值为“false”的“已订阅”cookie。你可以单击读取 cookie 按钮以获取 cookie。

In the below code, we set the 'subscribed' cookie with a 'false' value. You can click the read cookies button to get the cookies.

<html>
<body>
	<p id = "output"> </p>
	<button onclick = "setCookies()"> Set Cookie </button> <br> <br>
	<button onclick = "readCookies()"> Read Cookies </button>
	<script>
		let output = document.getElementById("output");
		function setCookies() {
			document.cookie = "subscribed=false"; // name-value pair
			output.innerHTML = "Cookie setting successful!";
		}
		function readCookies() {
			const allCookies = document.cookie.split("; ");
			output.innerHTML = "The subscribed cookie is - <br>";
			for (const cookie of allCookies) {
				const [name, value] = cookie.split("=");
				if (name == "subscribed") {
					output.innerHTML += `${name} : ${decodeURIComponent(value)} <br>`;
				}
			}
		}
	</script>
  </body>
</html>

Cookie’s Path Attribute

路径属性用于设置 cookie 的范围。它定义了应在网站上的何处访问 cookie。你可以将相对路径或绝对路径设置为路径属性值。

The Path attribute is used to set the scope of the cookie. It defines where cookies should be accessible on the website. You may set the relative or absolute path as a Path attribute value.

如果你设置相对路径,则可以在特定目录或子目录的任何地方访问所有 cookie。

If you set the relative path, all the cookies can be accessible everywhere in the particular or sub-directory.

Syntax

遵循以下语法在 cookie 中设置路径属性。

Follow the syntax below to set the Path attribute in the cookie.

document.cookie = "name=value;path=pathStr";

在上述语法中,你需要将“pathStr”替换为实际路径字符串。

In the above syntax, you need to replace the 'pathStr' with the actual path string.

Example

在下面的代码中,我们设置了 cookie 的路径。此处,我们设置了“/”(home 路由)。因此,可以在网站的每个网页上访问 cookie。你可以尝试在网站的不同网页上获取 cookie。

In the below code, we set the path for the cookie. Here, we set the ‘/’ (home route). So, cookies can be accessible on each webpage of the website. You may try to get the cookie on the different web pages of the website.

<html>
<body>
	<button onclick = "setCookies()"> Set Cookie </button>
	<p id = "output"> </p>
	<button onclick = "readCookies()"> Read Cookies </button>
	<script>
		let output = document.getElementById("output");
		function setCookies() {
			document.cookie = "signIn=true; path=/";
			output.innerHTML = "Cookie set successful!";
		}
		function readCookies() {
			const allCookies = document.cookie.split("; ");
			output.innerHTML = "The cookie is : <br>";
			for (const cookie of allCookies) {
				const [key, value] = cookie.split("=");
				if (key == "signIn") {
					output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
				}
			}
		}
	</script>
</body>
</html>

“expires”属性用于设置 cookie 的到期日期。它将日期字符串作为值。

The 'expires' attribute is used to set the expiry date for the cookie. It takes the date string as a value.

Syntax

遵循以下语法在 cookie 中设置 expires 属性。

Follow the syntax below to set the expires attribute in the cookie.

document.cookie = "name=value;expires=dateStr";

在上述语法中,你需要将“dateStr”替换为日期字符串。

In the above syntax, you need to replace the 'dateStr' with the date string.

Example

在下面的代码中,我们设置了 product cookie。此外,我们设置了 2050 年的到期日期。

In the code below, we set the product cookie. Also, we set the expiry date in 2050.

你可以尝试设置过去的到期日期并尝试访问 cookie。你将无法找到 cookie。

You may try to set the past expiry date and try to access the cookie. You won’t be able to find the cookie.

<html>
<body>
	<p id = "output"> </p>
	<button onclick = "setCookies()"> Set Cookie </button> <br> <br>
	<button onclick = "readCookies()"> Read Cookies </button>
	<script>
		let output = document.getElementById("output");
		function setCookies() {
			document.cookie = "product=mobile;expires=12 Jan 2050 12:00:00 UTC";
			output.innerHTML = "Cookie Set Successful!";
		}
		function readCookies() {
			const allCookies = document.cookie.split("; ");
			output.innerHTML = "The cookie is : <br>";
			for (const cookie of allCookies) {
				const [key, value] = cookie.split("=");
				if (key == "product") {
					output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
				}
			}
		}
	</script>
</body>
</html>

Cookie’s maxAge Attribute

“maxAge”属性是“expires”属性的替代方法。它用于指定 cookie 的生存期。它以秒为单位获取值。

The 'maxAge' attribute is an alternative to the 'expires' attribute. It is used to specify the lifetime of the cookie. It takes the seconds as a value.

当 cookie 的生命周期结束时,它将被自动删除。

When the lifetime of the cookie is finished, it will automatically get deleted.

Syntax

遵循以下语法将“maxAge”特性传递给 cookie。

Follow the syntax below to pass the 'maxAge' attribute to the cookie.

document.cookie = "name=value;max-ge=age;";

在上述语法中,您需要将“age”替换为秒数。

In the above syntax, you need to replace the 'age' with the number of seconds.

Example

在下面的代码中,我们将总秒数设置为 10 天,作为 maxAge 特性的值。您可以为 cookie 设置 1 秒的生存期,并尝试在 1 秒后访问该 cookie。

In the below code, we set the total number of seconds equal to 10 days as a value of the maxAge attribute. You can set the lifetime of 1 second for the cookie and try to access the cookie after 1 second.

<html>
<body>
	<button onclick = "setCookies()"> Set Cookie </button>
	<button onclick = "readCookies()"> Read Cookies </button>
	<p id = "output"> </p>
	<script>
		const output = document.getElementById("output");
		function setCookies() {
			document.cookie = "token=1234wfijdn;max-age=864000";
		}
		function readCookies() {
			const allCookies = document.cookie.split("; ");
			output.innerHTML = "The cookie is : <br>";
			for (const cookie of allCookies) {
				const [key, value] = cookie.split("=");
				if (key == "token") {
					output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
				}
			}
		}
	</script>
</body>
</html>

域特性用于指定 cookie 所适用的域名。您所提出请求中的域的默认值。您可以设置域特性来设置子域。

The domain attribute is used to specify the domain for which the cookie is valid. The default value of the domain from which you are making a request. You may set the domain attribute to set the subdomains.

Syntax

遵循以下语法在 cookie 中设置域特性的值。

Follow the syntax below to set the value of the domain attribute in the cookie.

document.cookie = "name=value;domain:domain_name ";

在上述语法中,将“domain_name”替换为实际域名,例如 example.com。

In the above syntax, replace the 'domain_name' with the actual domain, like example.com.

Example

在下面的代码中,我们为 cookie 设置“tutorialspoint.com”域名。

In the below code, we set the 'tutorialspoint.com' domain for the cookie.

<html>
<body>
	<p id = "output"> </p>
	<button onclick = "setCookies()"> Set Cookie </button>
	<button onclick = "readCookies()"> Read Cookies </button>
	<script>
		const output = document.getElementById("output");
		function setCookies() {
			document.cookie = "username=abcd;domain:tutorialspoint.com";
		}
		function readCookies() {
			const allCookies = document.cookie.split("; ");
			output.innerHTML = "The cookie is : <br>";
			for (const cookie of allCookies) {
				const [key, value] = cookie.split("=");
				if (key == "username") {
					output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
				}
			}
		}
	</script>
</body>
</html>

同样,您还可以更新特性值。例如,您可以延长 cookie 的过期时间。

Similarly, you can also update the attribute values. For example, you can extend the expiry time of the cookie.