Home  >  Article  >  Web Front-end  >  JavaScript uses localStorage to store data

JavaScript uses localStorage to store data

WBOY
WBOYforward
2022-08-05 11:54:333387browse

This article brings you relevant knowledge about javascript, which mainly introduces JavaScript's use of localStorage to store data. The sample code in the article is introduced in great detail and has certain reference value. I hope it will be useful to everyone. helpful.

JavaScript uses localStorage to store data

[Related recommendations: javascript video tutorial, web front-end

Background

In the past, js used Session and Cookie to store information, as if I was still stuck at that time, When I asked my colleagues if they had any new solutions, I learned that there is already HTML5 localStorage local storage, which can store data on the browser side.

I remember the earliest Cookies could only store very small things, about 4KB, and the security was very poor. In the IE6 era, a domain name could only hold 20 cookies. Cookies, the restrictions are quite large. Of course, IE also has userData, which is of no use. Flash also comes with a Storage, which is relatively large and has about 25 times the space of Cookie. At that time, Flash was also abandoned now.

In the H5 era, it will be unified, LocalStorage will dominate the world. The official recommendation is that each website is 5MB , which is very large. Although browser settings will vary, it is generally enough to store some JSON or strings or cache.

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 and will be used the next time you visit the website. At this time, the web page can directly read the previously saved data. Except for the different storage periods, the properties and methods of the two objects are exactly the same.

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

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

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

Storage operation

The data saved by sessionStorage and localStorage are all represented by "Key-Value key-value pairs" form exists. In other words, each item of data has a key name and a corresponding value. All data are saved in text format.

//sessionStorage 操作
sessionStorage.setItem("key","value");     // setItem方法,存储变量名为key,值为value的变量
var valueSession = sessionStorage.getItem("key");  // getItem方法,读取存储变量名为key的值
sessionStorage.removeItem('key');      // removeItem方法,删除变量名为key的存储变量
sessionStorage.clear();        // clear方法,清除所有保存数据
//localStorage 操作
localStorage.setItem("key","value");     // 存储变量名为key,值为value的变量
localStorage.key = "value"        // 同setItem方法,存储数据
var valueLocal = localStorage.getItem("key");   // 读取存储变量名为key的值
var valueLocal = localStorage.key;      // 同getItem,读取数据
localStorage.removeItem('key');      // removeItem方法,删除变量名为key的存储变量
localStorage.clear();         // clear方法,清除所有保存的数据

// 利用length属性和key方法,遍历所有的数据
for(var i = 0; i < localStorage.length; i++)
{
 console.log(localStorage.key(i));
}

// 存储 localStorage 数据为 Json 格式
value = JSON.stringify(jsonValue);      // 将 JSON 对象 jsonValue 转化成字符串
localStorage.setItem("key", value);     // 用 localStorage 保存转化好的的字符串

// 读取 localStorage 中 Json 格式数据
var value = localStorage.getItem("key");    // 取回 value 变量
jsonValue = JSON.parse(value);      // 把字符串转换成 JSON 对象

Storage event

When the stored data changes, the storage event will be triggered. We can specify a callback function for this event.

window.addEventListener("storage",onStorageChange);

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

function onStorageChange(e)
{
  console.log(e.key); 
}

In addition to the key attribute, the event object has three attributes:

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

Special note is that this event is not triggered on the current page that causes data changes. If the browser opens multiple pages under a domain name at the same time, when one of the pages changes the data of sessionStorage or localStorage, the storage events of all other pages will be triggered, and the storage event will not be triggered by the original page. Through this mechanism, communication between multiple windows can be achieved. Among all browsers, except IE, it will trigger the storage event on all pages.

Extended knowledge

1. localStorage and sessionStorage are two storage methods provided by HTML5 web storage. They are available in IE7 and above and most browsers. All servers support

2. The difference between localStorage and sessionStorage:

(1) LocalStorage and sessionStorage are both objects used to store temporary information on the client.

(2). They can only store objects of string type (although other native types of objects can be stored in the specification, but so far no browser has implemented it).

(3). The localStorage life cycle is permanent, which means that unless the user clears localStorage information on the UI provided by the browser, this information will exist forever. (recorded in memory)

The sessionStorage life cycle is the current window or tab. Once the window or tab is closed, all data stored through sessionStorage will be cleared (session storage)

(4), Different browsers cannot share information in localStorage or sessionStorage. Different pages in the same browser can share the same localStorage (the pages belong to the same domain name and port), but sessionStorage information cannot be shared between different pages or tabs.

It should be noted here that pages and tabs only refer to top-level windows. If a tab page contains multiple iframe tags and they belong to the same source page, then sessionStorage can be shared between them. (Same origin principle)

3. The size of data that can be stored by localStorage and sessionStorage is generally 5MB

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of JavaScript uses localStorage to store data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete