The difference and use between cookie, localStorage, sessionStorage, application cache

Web storage

HTML5 adds two new storage methods: localStorage and sessionStorage. Before that, cookies were mainly used for storage. Let's talk about the differences and application scenarios of the three below:

cookies storage

Introduction

Cookies are actually a small text data (no more than 4KB). Each browser will have a special folder to store cookie data. The content of cookies mainly includes key/value values ​​and is used to control cookie validity, security, and scope of use. It consists of several optional attributes. We can see the cookie in the browser.
Insert picture description here
The general composition and function of a cookie record are as follows

composition
  • Namge/Value: Set the name of the Cookie and the corresponding value. For the authentication Cookie, the Value value includes the access token provided by the Web server.
  • Expires/Max-Age: Set the cookie lifetime (GMT format). By default, the attribute value is a session cookie, which is only stored in the client's memory and expires when the user closes the browser; persistent cookies will be stored in In the user's hard disk, it will not become invalid until the lifetime expires or the user directly clicks the "Logout" button on the web page to end the session. Max-Age is the name in the http/1.1 protocol, and the unit is second. There are three possible values ​​for max-age: negative, 0, and positive. Negative number: valid period session; 0: delete cookie; positive number: valid period is creation time + max-age.
  • Path: defines the directory where the cookie can be accessed on the Web site.
  • Domain: Specifies the website or domain that can access the cookie. Domain prohibits the setting of generic top-level domain names such as .org.com , mainly to reduce the scope of cookie attacks.
  • Secure: Specify whether to use the HTTPS security protocol to send cookies. If set, it is equivalent to only inserting cookie data into the request when sending a secure request (https). Using the HTTPS security protocol can protect Cookies from being stolen and tampered with during the transmission process between the browser and the Web server.
  • HTTPOnly: Prevent client-side scripts from accessing cookies through the document.cookie attribute, which helps protect cookies from being stolen or tampered with by cross-site scripting attacks.

For more information about Cookies and security protection, please refer to Baidu Encyclopedia

Application scenario

The data in the cookie is automatically put into the http request every time a browser request is sent. The browser has related configuration switches to determine whether each request needs to include these cookie data. Based on this feature, the cookie is And store the data that must be transmitted for each request, such as identity authentication information.

Manipulate cookies

We can get or set non-HttpOnly cookie data by executing document.cookie on the console , and use semicolons to separate the data attributes.

If you want to modify a cookie, you only need to re-assign the value, the old value will be overwritten by the new value. But it should be noted that when setting a new cookie, the path/domain options must remain the same as the old cookie. Otherwise, the old value will not be modified, but a new cookie will be added.

Deleting a cookie is also quite simple, and it is also reassigned, as long as the expires option of this new cookie is set to a point in time in the past. But also note that the path/domain/ options must remain the same as the old cookie.

Note: The comma, semicolon, and space in the cookie are all regarded as special symbols. If these 3 special characters exist in the key and value, they need to be encoded with escape and decoded with unescape.

localStorage

localStorage is data storage with no time limit, and the storage space is generally 5M
Insert picture description here

Common method

  • Save data: localStorage.setItem(key,value);
  • Read data: localStorage.getItem(key);
  • Delete a single data: localStorage.removeItem(key);
  • Delete all data: localStorage.clear();
  • Get the key of an index: localStorage.key(index);
  • Determine whether there is a property value: localStorage.hasOwnProperty(key);

The data in localStorage is stored in a key/value way, we can directly use. or [] to access the value of the specified key, as follows:

// 更推荐采用.setItem,.getItem的方式获取
localStorage.name = 'myname'
localStorage['name'] //myname

By default, the value of localStorage can only store strings. We can store arrays or objects through JSON conversion.

var users = [
    {
        name: "xiaoming",
        grade: 1
    },
    {
        name: "teemo",
        grade: 3
    }
]
//写入
var usersStr = JSON.stringify(users);
localStorage.user = usersStr
//读取
var newUser = JSON.parse(localStorage.user)

sessionStorage

For the data storage of a session, when the browser is closed or the webpage is closed, the stored data will be cleared, and the storage space is generally 5M.
Insert picture description here

Common method

  • Save data: sessionStorage.setItem(key,value);
  • Read data: sessionStorage.getItem(key);
  • Delete a single data: sessionStorage.removeItem(key);
  • Delete all data: sessionStorage.clear();
  • Get the key of an index: sessionStorage.key(index);

Note : The only difference between localStorage and sessionStorage is that the length of time the two store data is different. When storing data, they are all stored in string mode, so pay attention to the type conversion problem when fetching data from storage.

H5 application cache

HTML5 provides application caching, by creating a cache manifest file to create an offline version of the web application. This means that we can access it offline.

Application caching depends on the manifest file, which tells the browser what is cached and what is not. The content of the file can be divided into three parts:

  • CACHE MANIFEST-The files listed under this heading will be cached after the first download
  • NETWORK-The files listed under this heading require a connection to the server and will not be cached
  • FALLBACK-The documents listed under this heading specify the fallback page when the page is inaccessible (such as a 404 page)

The following is an example of a manifest file:

CACHE MANIFEST        
# 2012-02-21 v1.0.0 这个是注释,更改注释也同样会促使浏览器更新缓存
/theme.css        
/logo.gif        
/main.js        
        
NETWORK:        
login.php        
        
FALLBACK:       
# 下面参数第一个url是资源,第二个是替补
/html/ /offline.html 

How to update the cache

After the application is cached, it will continue to keep the cache, knowing the following:

  • The user clears the browser cache (clear cache)
  • The manifest file is modified
  • Program update application cache

Application caching advantages

  • Offline browsing-users can use them while the app is offline
  • Speed-cached resources load faster
  • Reduce server load-the browser will only download updated or changed resources from the server.

Note : If the file we cache on the server is modified, the browser will not update the cache, so we need to update the manifest file to trigger the cache update.

Usage scenarios of HTML5 application cache

Application caching is mainly to provide caching of static resources (static pages, css, images, etc.). When there are some elements or resources that rarely change on the page, they can be cached in the form of application caching to avoid repeated requests. Reduce server load.

Reference link

Cookie introduction

App cache

Guess you like

Origin blog.csdn.net/dypnlw/article/details/115024799