Must-Know LocalStorage
Category Programming Technology
HTML API
LocalStorage in browsers has two APIs: localStorage and sessionStorage, which exist in the window object: localStorage corresponds to window.localStorage, and sessionStorage corresponds to window.sessionStorage.
The main difference between localStorage and sessionStorage is their lifespan.
Basic Usage
-
The term "scope" here refers to: how to isolate localStorage between different pages (you can't read Tencent's localStorage on Baidu's page, haha).
-
localStorage can be read/modified as long as it is under the same protocol, same hostname, and same port.
-
sessionStorage is stricter than localStorage; in addition to the protocol, hostname, and port, it also requires being in the same window (i.e., browser tab).
Lifespan
Theoretically, localStorage is permanent unless actively cleared. Even if the data exceeds the browser's size limit, it will not clear old data but will throw an error. However, it is unreliable on mobile browsers or WebView in Native Apps and may be cleared for various reasons (e.g., exiting the app, network switching, low memory). sessionStorage is cleared when the browser is closed (including the browser tab). Due to its short lifespan, sessionStorage has limited use cases, but it is less prone to anomalies and is more reliable.
Data Structure
LocalStorage is a standard key-value (KV) data type, simple yet extensible. Any object can be stored by converting it to a string using a certain encoding method. For example, converting an object to a JSON string allows storing the object; converting an image to a DataUrl (base64) allows storing the image. The uniqueness of keys is also important; reassigning the same key will overwrite the previous value.
Expiration Time
Unfortunately, localStorage does not natively support setting expiration times. To set an expiration time, you need to encapsulate logic to achieve this:
function set(key, value) {
var curtime = new Date().getTime(); // Get current time
localStorage.setItem(key, JSON.stringify({ val: value, time: curtime })); // Convert to JSON string
}
function get(key, exp) { // exp is the expiration time
var val = localStorage.getItem(key); // Get stored element
var dataobj = JSON.parse(val); // Parse JSON object
if (new Date().getTime() - dataobj.time > exp) { // If current time - time when element was created > expiration time
console.log("expires"); // Notify expiration
} else {
console.log("val=" + dataobj.val);
}
}
Capacity Limit
The industry standard is currently 5MB, much larger than cookies' 4KB. Use it wisely.
Domain Restriction
Due to browser security policies, localStorage cannot be cross-domain, nor can subdomains inherit localStorage data from parent domains, unlike cookies.
Exception Handling
localStorage is not entirely stable in current browser environments and may have various bugs. It is crucial to handle exceptions. I believe localStorage is an optimization for local resource storage, and using it should not compromise program usability. I strongly oppose just outputting error messages in the console. Exception handling for localStorage is typically done with try/catch.
How to Test if a User's Browser Supports LocalStorage
The common approach is to check if window.localStorage exists. However, some browsers have bugs, and even if they "support" localStorage, they may have low-level bugs like failing to setItem(). Therefore, I suggest testing support by set/getting a test item within a try/catch structure. Remember to delete the test data afterward.
Browser Compatibility
| Feature | Chrome | Firefox | Internet Explorer | Opera | Safari | Android | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|---|
| localStorage | 4 | 3.5 | 8 | 10.50 | 4 | 2.1 | 11 | iOS 3.2 |
| sessionStorage | 5 | 2 | 8 | 10.50 | 4 | 2.1 | 11 | iOS 3.2 |
How to Debug
In Chrome Developer Tools, under the Resources - Local Storage panel and Resources - Session Storage panel, you can see the localStorage data for the current domain.
Unable to Repeatedly setItem() on iOS Devices
>
Sometimes, setting setItem() on iPhone/iPad may throw a QUOTA_EXCEEDED_ERR error. Removing the item with removeItem() before setting it usually resolves this.
Recommended Plugins
-
-
-
Reference Articles
-
-
-
>
Original link: https://segmentfault.com/a/1190000004121465
** Click to Share Notes
-
-
-