乐闻世界logo
搜索文章和话题

What is the default expiration time of a cookie

1个答案

1

The default expiration time for cookies is not explicitly defined; it depends on how the cookies are created. Typically, if cookies are created without explicitly specifying an expiration time (Expires) or a validity period (Max-Age), they become session cookies. Session cookies store information that is only available during the browser session and are deleted when the browser window is closed.

If you want the cookies to remain after the browser is closed, you must specify an expiration time (Expires) or a validity period (Max-Age) when setting the cookies. For example:

javascript
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC";

In this example, the username cookie is set with an explicit expiration time, specifically December 18, 2023, at 12:00:00 UTC. After this time, the cookie automatically expires.

Alternatively, use the Max-Age attribute to specify the number of seconds the cookie is valid:

javascript
document.cookie = "username=JohnDoe; max-age=3600";

Here, max-age=3600 indicates that the cookie is valid for 3600 seconds (i.e., 1 hour) from the time it is created. After this period, the cookie automatically expires.

In summary, the default expiration time for cookies depends on whether an expiration method is specified during setting. If not specified, it becomes a session cookie that is deleted when the browser is closed; if specified, it expires according to the set time or duration. This flexibility allows developers to control the cookie's lifecycle as needed.

2024年8月12日 13:53 回复

你的答案