Home > Web Front-end > JS Tutorial > body text

Organize the application of cookie operation objects in JavaScript

WBOY
Release: 2022-08-05 11:35:33
forward
1452 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces issues related to the application of cookie operation objects. Cookies provide a useful way for Web applications to save user-related information. Let’s take a look at the method below, I hope it will be helpful to everyone.

Organize the application of cookie operation objects in JavaScript

[Related recommendations: javascript video tutorial, web front-end

How to operate cookies in Javascript

Cookies provide a useful way for Web applications to save user-related information. For example, when a user visits our site, cookies can be used to save user preferences or other information so that the next time the user visits our site, the application can retrieve the previously saved information.

What the heck is a cookie

A cookie is a small piece of text information that is passed between the web server and the browser along with user requests and pages. The information contained in the cookie can be read by the web application each time the user visits the site.

Cookies appear to solve the problem of saving user information. For example

  • When a user visits a web page, the user's name can be stored in a cookie.

  • The cookie will remember the username the next time the user visits the page.

Cookies can remember user information across all web pages. It contains information in the form of a string and is saved in the form of key-value pairs, that is, in the key=value format. Each cookie is usually separated by ";".

username = Daisy Green
Copy after login

Cookie Disadvantages

Cookies may be disabled. When a user pays great attention to personal privacy protection, he is likely to disable the cookie function of the browser;

Cookies are related to the browser. This means that even if you visit the same page, cookies saved by different browsers cannot be accessed by each other;

cookies may be deleted. Because each cookie is a file on the hard disk, it is likely to be deleted by the user;

Cookie security is not high enough. All cookies are recorded in files in the form of plain text, so if you want to save username, password and other information, it is best to encrypt it in advance.

How Cooke works

The server sends some data to the visitor's browser in the form of a cookie. If your browser allows cookies to be accepted. It is stored on the visitor's hard drive as a plain text record.

When a visitor jumps to another page, the browser will send the same cookie to the server for retrieval. Once it is retrieved, your server knows or remembers what was previously stored.

Composition of Cookie

Cookie In the HTTP header information, the header format of HTTP Set-Cookie is as follows:

Set-Cookie: name=value; [expires=date]; [path=path];
[domain=domainname]; [secure];
Copy after login

In the HTTP code A specific example:

<meta http-equiv="set-cookie" content=" cookieName = cookieValue;
expires=01-Dec-2006 01:14:26 GMT; path=/" />
Copy after login

As can be seen from the above format, Cookie consists of the following parts.

Name/Value pair

Name/Value is separated by a semicolon. A cookie can have up to 20 pairs. Each web page can have at most one cookie. The length of Value should not exceed 4K. For Value values, it is best to encode them with encodeURIComponent.

Domain

Domain domain name is also part of the cookie. By default, the domain name of the web page visited by the user will be stored in the cookie. If the domain name value of this cookie is set, it means that all servers on the domain name, not just the server you are visiting, can access this cookie. Generally, you should not do this. The format of setting the domain name is as follows: domain=http://xyz.com

path

Set the web pages in which directory for a specific server to access cookies. The format of setting the path is: path = /movies

Expires

Set the cookie survival time. By default, the cookie is automatically deleted when the user closes the browser. If not Set the cookie expiration time so that the cookie disappears when the user closes the browser. If you set this item, you can extend the cookie life. Set the time in js using the GMT form of the Date object. The format is as follows: expires = date.toGMTString()

Secure

Take the true or false value. If true, the cookie must be sent over https.

js Cookie

In JS, you can use the cookie attribute of the Document object to manipulate cookies. JS can read, create, modify and delete the cookies of the current web page. Let’s take a look at the specific operations.

Create Cookie

JS can use the document.cookie attribute to create a cookie. You can create a cookie in the following ways:

document.cookie = "username=Daisy Green";
Copy after login

You can also add a valid date ( UTC time). By default, cookies are deleted when the browser is closed:

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC";
Copy after login

Through the path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC"; path=/";
Copy after login

Read Cookie

Through JS, you can read cookies like this:

var x = document.cookie;
Copy after login

document.cookie 会在一条字符串中返回所有 cookie,比如:cookie1=value; cookie2

事例:

<html>
   <head>   
      <script type = "text/JavaScript">
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
                
               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(&#39;;&#39;);
                
               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split(&#39;=&#39;)[0];
                  value = cookiearray[i].split(&#39;=&#39;)[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>      
   </head>
    
   <body>     
      <form name = "myform" action = "">
         <p> click the Button to View Result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>      
   </body>
</html>
Copy after login

改变 cookie

通过使用 JS,咱们可以像创建 cookie 一样改变它:

document.cookie = "username=Steve Jobs; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";
Copy after login

这样旧 cookie 会被覆盖。

事例:

<html>
   <head>   
      <script type = "text/JavaScript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
                
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>      
   </head>
    
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>
Copy after login

删除 cookie

删除 cookie 非常简单,不必指定 cookie 值:直接把 expires 参数设置为过去的日期即可:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Copy after login

应该定义 cookie 路径以确保删除正确的 cookie。如果不指定路径,有些浏览器不会让咱们删除 cookie。

事例:

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
                
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write("Setting Cookies : " + "name=" + cookievalue );
            }
          //-->
      </script>      
   </head>
    
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of Organize the application of cookie operation objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template