preface

Sometimes we write projects that need to store certain commonly used data in the browser cache to improve performance. So how to store data in the browser? This article introduces several ways to store data in the browser, as well as the similarities and differences between them.

SessionStorage and localStorage

Let’s look at what Web Storage is.

Web Storage has the following two mechanisms:

  • sessionStorageFor each given Origin, a separate storage area is maintained that is available for the duration of the page session (that is, as long as the browser is open, including page reloads and resumes).
  • localStorageSame functionality, but data remains after the browser closes and then opens again.

The two mechanisms are used with the window. sessionStorage and window. localStorage properties (more specifically, In supported browsers the Window object implements WindowLocalStorage and WindowSessionStorage objects and hangs under their localStorage and sessionStorage properties) — calling either object creates Storage object, through which you can set, obtain, and remove data items. Use different Storage objects for each Origin sessionStorage and localStorage — run and controlled independently.

Advantages of WebStorage:

(1) Larger storage space: cookie is 4KB, while WebStorage is 5MB;

(2) Save network traffic: WebStorage will not be transmitted to the server, stored in the local data can be directly obtained, not like cookies every request will be transmitted to the server, so reduce the interaction between the client and the server, saving network traffic;

(3) sessionStorage is very convenient for data that only needs to be saved during browsing a set of pages but can be discarded after closing the browser;

(4) Fast display: some data stored in the WebStorage, plus the browser itself cache. It’s much faster to get data locally than it is to get data from the server.

(5) security: WebStorage will not be sent to the server with the HTTP header, so the security is relatively higher than the cookie, will not worry about interception, but there are still forged problems;

(6) WebStorage provides some methods, data operation is more convenient than cookie;

“Example” :

The following code snippet accesses the localStorage object under the current domain name and adds a data item via localstorage.setitem (). (same as sessionStorage)

localStorage.setItem('myCat'.'Tom');
Copy the code

This syntax is used to read the localStorage entry as follows:

let cat = localStorage.getItem('myCat');
Copy the code

This syntax is used to remove the localStorage item as follows:

localStorage.removeItem('myCat');
Copy the code

This syntax is used to return the NTH key name in the store as follows:

localStorage.key(0)
Copy the code

This syntax is used to remove all localStorage entries as follows:

// Remove alllocalStorage.clear();
Copy the code

Similarities:

  • The data size of localStorage and sessionStorage is generally5MB.
  • LocalStorage and sessionStorage are both localStorage and stored inThe client, does not interact with the server.
  • LocalStorage and sessionStorage can only be storedString typeFor complex objects, you can use Stringify and Parse for JSON objects provided by ECMAScript.

“Difference” :

  • LocalStorage Life cycle yespermanent, unless they delete or clear the cache, while sessionStorage is only inThe current sessionThe command is valid and will be cleared after you close the page or browser.
  • Different pages of the browser can share the same localStorage (pages belong to the same domain name and port), but different pages or tabs cannot share the sessionStorage information.
  • LocalStoragese is often used for long-term login (+ determine whether the user has logged in), suitable for long-term storage of local data, while sessionStorage-sensitive account one-time login.

Web Storage Note:

  • Web Storage can only store strings. JSON data can be accessed using json.stringify () and json.parse ().
  • If setItem is disabled, try… Catch c.

cookie

Wikipedia says Cookies, also known as “Cookies.” The type is “small text file”, which refers to the data (usually encrypted) that some websites store on the user’s Client Side to identify the user. Invented by Lou Monterey, a former Netscape employee, in March 1993. Originally defined in RFC 2109. The most widely used Cookie standard is not defined in the RFC, but is an extension of the netscape standard.

Again, let’s talk about setting cookies and getting cookies.

Create cookies as follows:

document.cookie="username=John Doe";
Copy the code

We can also add an expiration time (in UTC or GMT time) to the cookie. By default, cookies are deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT";
Copy the code

You can also use the path parameter to tell the browser the path of the cookie. By default, cookies belong to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
Copy the code

Deleting cookies is very simple. You just need to set the Expires parameter to a previous time, as shown below, Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
Copy the code

For convenience, we can encapsulate some methods as a function. For example, here we encapsulate the methods for setting cookies and getting cookies.

“Function to set cookie value” :

// This function sets the cookie name, cookie value, and cookie expiration timefunction setCookie(cname,cvalue,exdays)
{
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
 var expires = "expires="+d.toGMTString();  document.cookie = cname + "=" + cvalue + "; " + expires; } Copy the code

“Function to get cookie value” :

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split('; ');
  for(var i=0; i<ca.length; i++) 
 {  var c = ca[i].trim();  if (c.indexOf(name)==0) return c.substring(name.length,c.length);  }  return ""; } Copy the code

Finally, let’s talk about cookies in context.

1. Cookie usage scenario

The client requests the server, and if the server needs to record the user’s state, it issues a Cookie to the client browser. The client browser saves the Cookie. When the browser requests the site again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to identify the user’s state. The server can also modify the contents of the Cookie as needed. (That is, you are given an ID card, which records your information, and before each communication with the background, the background will check whether your ID card has expired before calling you.)

2. Cookie is not cross-domain

Since all this information is stored in our client (browser), then the browser stored so many cookies, won’t chaos, for example, I visit the QQ website, took ali’s cookie (ID card), the past?

The answer is no, the browser is qualified or not, is to see whether its cookie will be stored and used well. Cookies that cross domains cannot be shared.

3. Cookie security

Since it is stored on the client, there will be the risk of modification. If the cookie is stored in plain text, I believe xiao Bai can also change the information at will (equivalent to changing your ID card to someone else’s name, and then pretending to be that person to communicate with the background).

Early cookie does exist such a problem, but certainly to progress, to encrypt, now your cookie above are garbled, only the background program to know how to decrypt the garbled code, into your identity, we modify will lead to your ID card invalid.

4. Cookie efficiency

Since we need to carry this cookie every time we visit the background, let’s assume that if our cookie is 5KB and I open the home page of a website, and the number of requests on the home page is more than 200, then in the process of opening the home page, 5KB ×200 = more than 1MB traffic will be consumed.

We’ve only opened one page, and the id verification alone has already consumed 1MB of traffic, not counting the 200 + requests for data, images, text and more, you can only open the home page for several MB.

Therefore, we need to compress the size of the cookie, so as not to put in unnecessary, too waste traffic and efficiency.

5. Similarities and differences between cookie, sessionStorage and localStorage

Similarities:

  • Cookies and sessionStorage and localStorage is stored in the browser, and homologous.

“Difference” :

  • Cookie data is always cognateCarried in the HTTP requestThat is, cookies are passed back and forth between the browser and the server, while sessionStorage and localStorage do not automatically send data to the server and only keep it locally. Cookie data also has the concept of path, which can restrict cookies to a specific path.
  • Storage size limits are also differentCookie data cannot exceed 4K, and because cookies are carried with each HTTP request, cookies are only suitable for storing very small data, such as session identifiers. SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more.
  • Different data validity periods, sessionStorage: only valid until the current browser window closes; LocalStorage: always valid, saved even when the window or browser is closed and therefore used as persistent data; Cookie: Only valid before the set cookie expiration time, even if the window is closed or the browser is closed
  • Different scope, sessionStorage is not shared in all origin Windows, localstorage is shared in all origin Windows; Cookies are also shared across all the same origin Windows.
  • Web Storage supportEvent notification mechanism, you can send notifications of data updates to listeners.
  • The API interface of web Storage is easier to use.

The actual use of cookies and sessionStorage and localStorage might look more like the following figure.

conclusion

Finally, use a table to make a summary 📝.

sessionStorage localStorage cookie
The life cycle Browser Shutdown Permanently exists unless you delete or clear the cache yourself Can be set by yourself, default to browser closed
Size limit 5MB 5MB 4K
Communicating with the server Only on the client side Only on the client side Every request is carried
security It’s higher than cookies, so you don’t have to worry about interception, but there are still counterfeiting problems It’s higher than cookies, so you don’t have to worry about interception, but there are still counterfeiting problems Low security (Cookie spoofing, Cookie interception)
Application scenarios Log in to a sensitive account once Often used for long-term logins (+ to determine whether a user is logged in) Determine whether the user has logged into the site

Reference article:

  • Introduction to the session cookie, sessionStorage and localStorage difference and application scenarios
  • This article is enough for an in-depth understanding of cookies and sessions.