SoFunction
Updated on 2025-03-01

JavaScript uses localStorage to store data

background

In the past, js wereSessionandCookie I came to store information, as if I was still at that time. When I asked my colleagues if there was a new solution, I realized that there was alreadyHTML5 localStorageLocal storage This thing can store data on the browser side.

Remember the earliestCookiesIt can only store very small things, with 4KB, and poor security. In the IE6 era, a domain name can only have twenty cookies, and the restrictions are quite large. Of course, IE also has userData things, which is useless. Flash also brought a Storage, which is relatively large, with a space of about 25 times that of cookies. At that time, Flash was abandoned.

In the H5 era, it was unified.LocalStorage Unify the World. Official recommendation is for each website 5MB , very big. Although the browser settings will be different, it is generally enough to store some JSON, strings or caches.

HTML5 LocalStorage Local Storage

  • sessionStorage:The saved data is used for a session of the browser. When the session ends (usually the window is closed), the data is cleared;
  • localStorage:The saved data exists for a long time. The next time you visit the website, the web page can directly read the previously saved data. Except for the different shelf life, the properties and methods of these two objects are exactly the same.

They are much like enhanced versions of the cookie mechanism, although they can use much larger storage space. However, like cookies, they are also subject to the same domain. The data stored in a certain web page can only be read by web pages in the same domain.

By checking whether the window object contains sessionStorage and localStorage properties, you can determine whether the browser supports these two objects.

function checkStorageSupport()
{
 // sessionStorage
 if () {
  return true;
 } else {
  return false;
 }
 
 // localStorage
 if () {
  return true;
 } else {
  return false;
 }
}

Storage Operation

The data saved by sessionStorage and localStorage are both as"Key-Value key-value pair"The form exists. That is to say, each item of data has a key name and a corresponding value. All data is saved in text format.

//sessionStorage operation("key","value");     // setItem method, store variable with variable named key and value of valuevar valueSession = ("key");  // getItem method, read the value of the stored variable name key('key');      // removeItem method, delete the stored variable with the variable named key();        // clear method, clear all saved data//localStorage operation("key","value");     //Storage variable with the value of the value = "value"        // Same setItem method to store datavar valueLocal = ("key");   // Read the value of the stored variable named keyvar valueLocal = ;      // same as getItem, read data('key');      // removeItem method, delete the stored variable with the variable named key();         // clear method, clear all saved data
// Use the length attribute and key method to traverse all datafor(var i = 0; i < ; i++)
{
 ((i));
}

// Store localStorage data in Json formatvalue = (jsonValue);      // Convert JSON object jsonValue into a string("key", value);     // Use localStorage to save the converted string
// Read Json format data in localStoragevar value = ("key");    // Retrieve the value variablejsonValue = (value);      // Convert string to JSON Object

Storage Events

The storage event is triggered when the stored data changes. We can specify the callback function for this event.

("storage",onStorageChange);

The callback function accepts an event object as an argument. The key attribute of this event object saves the changed key name.

function onStorageChange(e)
{
  (); 
}

In addition to the key attribute, there are three properties of the event object:

  • oldValue: The value before update. If the key is newly added, this property is null.
  • newValue: updated value. If the key is deleted, this property is null.
  • url: The URL of the webpage that originally triggered the storage event.

!!!It is particularly noteworthy that the event is not triggered on the current page that caused the data to change. If the browser opens multiple pages under a domain name at the same time, when one of the pages changes the sessionStorage or localStorage data, the storage events of all other pages will be triggered, and the original page does not trigger the storage event. This mechanism can be used to realize communication between multiple windows. Among all browsers, except for IE browser, it will trigger storage events on all pages.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.