Home Web Front-end JS Tutorial Detailed introduction to the use of document.cookie in Javascript

Detailed introduction to the use of document.cookie in Javascript

Mar 22, 2017 pm 02:35 PM

This article mainly introduces the use of document.cookie in Javascript, and the function of remembering passwords and saving passwords through cookies. Friends in need can refer to the following

Set cookie

Each cookie is a name/value pair. You can assign the following string to document.cookie:

document.cookie="userId=828";
Copy after login

If you want to store multiple name/value pairs at one time, you can use semicolons and spaces (;) to separate them, for example:

document.cookie="userId=828; userName=hulk";
Copy after login

You cannot use semicolons (;) or commas (, ), equal sign (=) and space.

It's easy to do this in the name of the cookie, but the value to be saved is undefined. How to store these values?

The method is to use escape()function for encoding. It can express some special symbols in hexadecimal. For example, spaces will be encoded as "20%", which can be stored in cookie value, and using this solution can also avoid the occurrence of Chinese garbled characters. For example:

document.cookie="str="+escape("I love ajax");
Copy after login

is equivalent to: document.cookie="str=I%20love%20ajax";

When using escape() encoding, you need to use unescape() after extracting the value. Only by decoding can you get the original cookie value, which has been introduced before. Although document.cookie looks like a property and can be assigned different values. But it is different from general attributes. Changing its assignment does not mean losing the original value. For example, executing the following two statements continuously:

document.cookie="userId=828";
document.cookie="userName=hulk";
Copy after login

At this time, the browser will maintain two cookies, namely userId. and userName, so assigning a value to document.cookie is more like executing a statement like this:

document.addCookie("userId=828");
document.addCookie("userName=hulk");
Copy after login

In fact, the browser sets the cookie in this way. If you want to change the value of a cookie, just re- Assign a value, for example:

document.cookie="userId=929";
Copy after login

This will set the cookie value named userId to 929.

Get the value of the cookie

The following describes how to get the value of the cookie. The value of the cookie can be obtained directly from document.cookie:

var strCookie=document.cookie;
Copy after login

This will obtain a string consisting of multiple name/value pairs separated by semicolons. These name/value pairs include the names under the domain name. All cookies. For example:

Copy after login

It can be seen that all cookie values ​​can only be obtained at one time, but the cookie name cannot be specified to obtain the specified value. This is the most troublesome part of processing cookie values.

Users must analyze this string themselves to obtain the specified cookie value. For example, to obtain the value of userId, this can be achieved:

Copy after login

In this way, the value of a single cookie is obtained

Using a similar method, you can get the value of one or more cookies. The main technique is still the related operations of strings and arrays.

Set the expiration date for cookies. Up to now, all cookies have been single-session cookies, that is, these cookies will be lost after the browser is closed. In fact, these cookies are only stored in memory without establishing a corresponding hard disk files.

In actual development, cookies often need to be saved for a long time, such as saving the user's login status. This can be achieved using the following options:

document.cookie="userId=828;
expires=GMT_String";
Copy after login

where GMT_String is a time string expressed in GMT format. This statement sets the userId cookie to the expiration time represented by GMT_String. After this time, the cookie will Disappeared and inaccessible. For example:

If you want to set a cookie to expire after 10 days, you can do it like this:

<script language="JavaScript" type="text/javascript">
<!-- //获取当前时间
var date=new Date();
var expireDays=10; //将date设置为10天以后的时间
date.setTime(date.getTime()+expireDays*24*3600*1000); //将userId和userName两个cookie设置为10天后过期
document.cookie="userId=828; userName=hulk;
expire="+date.toGMTString(); //-->
</script>
Copy after login

Delete cookie

For To delete a cookie, you can set its expiration time to a past time, for example:

<script language="JavaScript" type="text/javascript">
<!--
//获取当前时间
var date=new Date();
//将date设置为过去的时间
date.setTime(date.getTime()-10000);
//将userId这个cookie删除
document.cookie="userId=828; expire="+date.toGMTString();
//-->
</script>
Copy after login

Specify the path to access the cookie. By default, if a cookie is created on a page, the page is Other pages in the directory can also access

this cookie. If there are subdirectories under this directory, you can also access it in the subdirectories.

In order to control the directory that cookies can access, you need to use the path parameter to set cookies. The syntax is as follows:

document.cookie="name=value; path=cookieDir";
Copy after login

where cookieDir represents the directory where cookies can be accessed. For example:

document.cookie="userId=320; path=/shop";
Copy after login

means that the current cookie can only be used in the shop directory.

If you want to make cookies available throughout the website, you can specify cookie_dir as the root directory, for example:

document.cookie="userId=320; path=/";
Copy after login

Specify the host name and path that can access the cookie. The host name refers to the same domain. Different hosts, for example: www.google.com and gmail.google.com are two different host names. By default, cookies created in one host cannot be accessed in another host, but they can be controlled through the domain parameter. The syntax format is:

document.cookie="name=value;
domain=cookieDomain";
Copy after login

Take Google as an example, To achieve cross-host access, you can write it as:

document.cookie="name=value;
domain=.google.com";
Copy after login

In this way, all hosts under google.com can access the cookie.

Comprehensive example: Constructing a general cookie processing function The cookie processing process is relatively complex and has certain similarities. Therefore, several functions can be defined to complete the common

operations of cookies, thereby achieving code reuse. Commonly used cookie operations and their function implementations are listed below.

1.添加一个cookie:addCookie(name,value,expireHours) 该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。

这里约定expireHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。该函数实现如下:

<script language="JavaScript" type="text/javascript">
<!--
function addCookie(name,value,expireHours){
       var cookieString=name+"="+escape(value);
       //判断是否设置过期时间
       if(expireHours>0){
          var date=new Date();
          date.setTime(date.getTime+expireHours*3600*1000);
          cookieString=cookieString+"; expire="+date.toGMTString();
       }
       document.cookie=cookieString;
}
//-->
</script>
Copy after login

2.获取指定名称的cookie值:getCookie(name)

该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下:

<script language="JavaScript" type="text/javascript">
<!--
function getCookie(name){
       var strCookie=document.cookie;
       var arrCookie=strCookie.split("; ");
       for(var i=0;i<arrCookie.length;i++){
          var arr=arrCookie[i].split("=");
          if(arr[0]==name)return arr[1];
       }
       return "";
}
//-->
</script>
Copy after login

3.删除指定名称的cookie:deleteCookie(name)

该函数可以删除指定名称的cookie,其实现如下:

<script language="JavaScript" type="text/javascript">
<!--
function deleteCookie(name){
       var date=new Date();
       date.setTime(date.getTime()-10000);
       document.cookie=name+"=v; expire="+date.toGMTString();
}
//-->
</script>
Copy after login

The above is the detailed content of Detailed introduction to the use of document.cookie in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles