html5 data storage (localStorage and sessionStorage)

Introduction

HTML5 provides two new methods for storing data on the client side, which are persistent data storage localStorage and conversational data storage sessionStorage.

localStorage object

The data stored by the localStorage object has no time limit, so it is called persistent storage, and data storage is available for a long time.
Before using such objects, it is best to check whether the browser supports it. The check code is as follows:

  if(typeof(Storage)!="undefined") {
               //是的! 支持 localStorage sessionStorage对象! //一些代码...}
 else { //抱歉! 不支持web存储。 }

The localStorage object and the sessionStorage object have the same methods, only the object names are different.

Common methods of localStorage objects:

localStorage.setItem(key,value):保存数据。
localStorage.getItem(key):读取数据。
localStorage.removeItem(key):删除单个数据。
localStorage.clear():删除所有数据。
localStorage.key(index):得到某个索引的key。

sessionStorage object

The sessionStorage object stores data for a session. The data storage cycle is short,When the user closes the browser window, the data will be deleted. The methods of this object are the same as those of the localStorage object.

Guess you like

Origin blog.csdn.net/weixin_46168350/article/details/112314798