Home > Article > Web Front-end > Detailed introduction to localstorage in html5 (picture)
localstorage has two types in the browser's API: localStorage and sessionStorage, which exist in the window object : localStorage corresponds to window.localStorage, and sessionStorage corresponds window.sessionStorage. . Next, this article will introduce to you the relevant information of localstorage of html5. Friends who need it can refer to
HTML API
localstorage has two browser APIs: localStorage and sessionStorage, which exist in the window object: localStorage corresponds to window.localStorage, and sessionStorage corresponds to window.sessionStorage.
The difference between localStorage and sessionStorage mainly lies in their lifetime.
Basic use of methods
localStorage.setItem("b","isaac");//设置b为"isaac" var b = localStorage.getItem("b");//获取b的值,为"isaac" var a = localStorage.key(0); // 获取第0个数据项的键名,此处即为“b” localStorage.removeItem("b");//清除b的值 localStorage.clear();//清除当前域名下的所有localstorage数据
Scope
The scope here refers to: how to isolate localStorage between different pages (it is impossible to read Tencent’s localStorage on Baidu pages) Yeah, hahaha).
localStorage can read/modify the same localStorage data as long as it is under the same protocol, the same host name, and the same port.
sessionStorage is more stringent than localStorage. In addition to the protocol, host name, and port, it also requires being in the same window (that is, the tab page of the browser).
Lifetime
Theoretically, localStorage is permanently valid, that is, it will not disappear if it is not actively cleared, even if the saved data exceeds If the size specified by the browser is exceeded, the old data will not be cleared and only an error will be reported. However, it should be noted that in the browser on the mobile device or the WebView used by each Native App, localStorage is unreliable and may fail due to various reasons (such as exitingApp, network switching , insufficient memory, etc.) are cleared.
As the name suggests, the lifetime of sessionStorage is similar to a session. As long as the browser is closed (including the browser tab), it will be cleared. Since the lifetime of sessionStorage is too short, its application scenarios are very limited, but on the other hand, it is not prone to abnormal situations and is relatively reliable.
Data structure
localstorage is a standard key-value pair (Key-Value, KV for short) Data type, Simple but easy to extend. As long as the object you want to store in localstorage is converted into a string using a certain encoding method, it can be easily supported. For example: convert the object into a json string to store the object; convert the picture into DataUrl (base64) to store the picture. In addition, for key-value data types, the feature "the key is unique" is also very important. If you assign the same key repeatedly, the last value will be overwritten.
Expiration time
Unfortunately, localstorage does not natively support setting the expiration time. If you want to set it, you can only encapsulate it yourself. A layer of logic is implemented:
function set(key,value){ var curtime = new Date().getTime();//获取当前时间 localStorage.setItem(key,JSON.stringify({val:value,time:curtime}));//转换成json字符串序列 } function get(key,exp)//exp是设置的过期时间 { var val = localStorage.getItem(key);//获取存储的元素 var dataobj = JSON.parse(val);//解析出json对象 if(new Date().getTime() - dataobj.time > exp)//如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间 { console.log("expires");//提示过期 } else{ console.log("val="+dataobj.val); } }
Capacity limit
The current industry is basically unified at 5M, which is already larger than cookie The 4K version of s is much larger, so use it sparingly.
Domain name restrictions
Due to the security policy of the browser, localstorage cannot cross domain, nor can it be used by sub-domains. The domain name inherits the localstorage data of the parent domain name. This is quite different from cookies.
Localstorage is not completely stable in the current browser environment, and various bugs may occur. You must consider exception handling. I personally think that localstorage is just an optimization method for resource localization. The use of localstorage cannot reduce the usability of the program. I am absolutely opposed to exception handling that only outputs an error message in the console. Localstorage exception handling generally uses try/catch to catch/handle exceptions.
How to test whether the user's current browser supports localstorage
The current common practice is to detect whether window.localStorage exists, but some browsers There are bugs. Although localstorage is "supported", low-level bugs such as being unable to setItem() may even occur in the actual process. Therefore, I suggest that you can determine whether the browser supports localstorage by setting/getting a test data in the try/catch structure to see if there are exceptions. Of course, remember to delete the test data after the test is completed.
Browser Compatibility
Resources - Local Storage panel and Resources - Session in chrome developer tools In the Storage panel, you can see the localstorage data under the current domain name.
setItem() cannot be repeated on ios devices
In addition, sometimes strange behavior occurs when setting setItem() on iPhone/iPad QUOTA_EXCEEDED_ERR error. Generally, removeItem() before setItem will be ok.The above is the detailed content of Detailed introduction to localstorage in html5 (picture). For more information, please follow other related articles on the PHP Chinese website!