The difference between cookie, localStorage and sessionStorage

Table of contents

1. The validity period of the storage time is different

Second, the storage size is different

3. Communication with the server

Fourth, the convenience of reading and writing operations

1、cookie

2、sessionStorage

3、localStorage


Cookie, localstorage , and sessionStorage are all methods for temporarily storing client session information or data . The following briefly introduces the differences between the three:

1. The validity period of the storage time is different

1. The validity period of the cookie can be set. By default, it will expire after closing the browser.

2. The validity period of sessionStorage is only kept on the current page, and it will become invalid after closing the current session page or browser

3. The validity period of localStorage is always valid without manual deletion

Second, the storage size is different

1. The cookie storage is about 4kb, and the storage capacity is relatively small. Generally, a page can store up to 20 pieces of information

2. The storage capacity of localStorage and sessionStorage is 5Mb (official introduction, there may be some differences with browsers)

3. Communication with the server

1. The cookie will participate in the communication with the server, and is generally carried in the header of the http request, such as some key key verification, etc.

2. localStorage and sessionStorage are pure front-end storage and do not participate in communication with the server

Fourth, the convenience of reading and writing operations

1、cookie

The cookie operation is cumbersome, and some data cannot be read

  • Creation of cookies (modification and creation are the same, creating the same name will overwrite the previous one)
//JavaScript 中,创建 cookie 如下所示:
document.cookie="username=John Doe";
//您还可以为 cookie 添加一个过期时间(以 UTC 或 GMT 时间)。默认情况下,cookie 在浏览器关闭时删除:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT";
//您可以使用 path 参数告诉浏览器 cookie 的路径。默认情况下,cookie 属于当前页面。
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
  • Reading of cookies
var x = document.cookie;
  • Deletion of cookies
//删除 cookie 非常简单。您只需要设置 expires 参数为以前的时间即可,如下所示,设置为 Thu, 01 Jan 1970 00:00:00 GMT:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

2、sessionStorage

  • store a piece of data
sessionStorage.setItem('数据名', '数据值');
  • read a piece of data
let data = sessionStorage.getItem('数据名');
  • clear a piece of data
sessionStorage.removeItem('数据名');
  • remove all data
sessionStorage.clear();

3、localStorage

  • store a piece of data
localStorage.setItem('数据名', '数据值');
  • read a piece of data
let data = localStorage.getItem('数据名');
  • clear a piece of data
localStorage.removeItem('数据名');
  • remove all data
localStorage.clear();

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/130435612