The difference between sessionStorage, localStorage, cookie

Common point: They
are all stored on the browser side and are of the same origin.
Differences:
1. The cookie data is always carried in the http request of the same origin (even if it is not needed).
That is, the cookie is passed back and forth between the browser and the server. The concept of path can limit the cookie to only belong to a certain path. SessionStorage and localStorage will not automatically send data to the server, but only save it locally.

2. The storage size limits are also different;
cookie data cannot exceed 4K, and because each http request carries cookies, cookies are only suitable for storing small data, such as session identifiers.
Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies and can reach 5M or more;

3. The data validity period is different;
sessionStorage: only valid before the current browser window is closed;
localStorage: always valid, the window or browser is closed and saved, so it is used as persistent data;
cookie: only valid before the set cookie expiration time, Even if the window is closed or the browser is closed

4. The scope is different;
sessionStorage is not shared in different browser windows, even the same page;
localstorage is shared
in all windows of the same origin ; cookie is also shared in all windows of the same origin;

5. Web Storage supports an event notification mechanism, which can send data update notifications to listeners.
6. Web Storage's api interface is more convenient to use

设置localStorage和sessionStorage:
localStorage.setItem(“beforeTime”)
sessionStorage.setItem(“beforeTime”)
读取localStorage和sessionStorage:
localStorage.getItem(“beforeTime”)
sessionStorage.getItem(“beforeTime”)

Guess you like

Origin blog.csdn.net/qq_43237014/article/details/106782037