Speaking of local storage, it’s taken a long time to get to HTML5, and here’s how it’s been:
The problem with the early Cookies, of course, was that they were too small, about 4KB in size, and IE6 only supported 20 Cookies per domain, which was too small. The advantage is that people support it, and they support it pretty well. The users who disabled cookies a long time ago are slowly disappearing, just as the users who disabled javascript did not exist.
UserData is IE stuff. Now the most used is Flash bar, the space is 25 times Cookie, basically enough. Then Google came out with Gears, and while there was no limit, there was a problem with installing extra plugins (which hadn’t been studied). The official recommendation is 5MB per site, which is pretty big, just a few strings, and that’s enough. The weird thing is that all the supported browsers currently use 5MB, although there are some browsers that users can set, but for web creators, 5MB is the right size for the current situation.
The support is shown above, IE 8.0 support, very surprising. Note that when testing Internet Explorer or Firefox, you need to upload the file to the server (or localhost), and directly click on the local HTML file.
The first, of course, is to check whether the browser supports local storage. In HTML5, localStorage is a window attribute, including localStorage and sessionStorage. The name should be clear to recognize the difference between the two. The former is always local, the latter is only with the session, once the window closes. They are used in the same way. The following uses localStorage as an example.
if(window.localStorage){
alert('This browser supports localStorage');
}else{
alert('This browser does NOT support localStorage');
}
Copy the code
To store data, add a property to window.localstorage, such as window.localstorage. a or window.localstorage [“a”]. Its read, write and delete operations are very simple, in the form of key-value pairs, as follows:
localStorage.a = 3;// Set a to "3"
localStorage["a"] = "sfsf";// Set a to "SFSF", overwriting the value above
localStorage.setItem("b"."isaac");// Set b to "Isaac"
var a1 = localStorage["a"];// Get the value of a
var a2 = localStorage.a;// Get the value of a
var b = localStorage.getItem("b");// Get the value of b
localStorage.removeItem("c");// Clear the c value
Copy the code
The most recommended uses here are, of course, getItem() and setItem(), and removeItem() is used to remove key-value pairs. If you want to clear all key-value pairs at once, use clear(). In addition, HTML5 provides a key() method, which can be used when the key value is not known, as follows:
var storage = window.localStorage;
function showStorage(a){
for(var i=0; i<storage.length; i++){//key(I) gets the corresponding key, and getItem() gets the corresponding value
document.write(storage.key(i)
+ ":" + storage.getItem(storage.key(i)) + "<br>"); }}Copy the code
Write the simplest counter that leverages local storage:
var storage = window.localStorage;
if(! storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount".0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;// Format conversion is required
document.getElementByIdx_x("count").innerHTML= storage.pageLoadCount;
showStorage();
Copy the code
It should be noted that HTML5 local storage can only store strings, any format of storage will be automatically converted to strings, so when reading, you need to do their own type conversion. That’s why parseInt had to be used in the previous code.
In addition, setItem() on iPhone/iPad sometimes causes a weird QUOTA_EXCEEDED_ERR error, so removeItem() is usually ok before setItem.
HTML5’s local storage also provides a storage event that can listen for changes in key/value pairs, using the following methods:
if(window.addEventListener){
window.addEventListener("storage",handle_storage,false);
}else if(window.attachEvent){
window.attachEvent("onstorage",handle_storage);
}
function handle_storage(e){
if(! e){e=window.event; }//showStorage();
}
Copy the code
For event variable E, it is a StorageEvent object that provides some useful properties for observing key-value pair changes.
Add two key-value pairs A and B, and add a button. Set a fixed value for A, and when the button is clicked, change the value of B:
<body>
<p>You have viewed this page <span id="count">0</span> time(s).</p>
<p><input type="button" value="changeStorage" onClick="changeS()"/></p>
<script>
var storage = window.localStorage;
if(! storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount".0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;// Format conversion is required
document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount;
showStorage();
if(window.addEventListener){
window.addEventListener("storage",handle_storage,false);
}else if(window.attachEvent){
window.attachEvent("onstorage",handle_storage);
}
function handle_storage(e){
if(! e){e=window.event; } showObject(e); }function showObject(obj){
// Display object recursively
if(! obj){return; }for(var i in obj){
if(typeof(obj[i])! ="object" || obj[i]==null){
document.write(i + ":" + obj[i] + "<br/>");
}else{
document.write(i + " : object" + "<br/>");
}
}
}
storage.setItem("a".5);
function changeS(a){
// Modify a key value to test the storage event
if(! storage.getItem("b")){storage.setItem("b".0); } storage.setItem('b',parseInt(storage.getItem('b')) +1);
}
function showStorage(a){
// Loop through the key-value pairs in localStorage
for(var i=0; i<storage.length; i++){//key(I) gets the corresponding key, and getItem() gets the corresponding value
document.write(storage.key(i)+ ":" + storage.getItem(storage.key(i)) + "<br>");
}
}
</script>
</body>
Copy the code
It turns out that the current browser support for this is not very good, only iPad and Firefox support, and Firefox support is a mess, e objects don’t have those properties at all. IPad support is very good, using E.uri (not E.ulu), Safari on desktop not working, weird.
At present, browsers have a good developer debugging function, the following are Chrome and Firefox debugging tools to view LocalStorage:
Additionally, javascript currently uses a wide variety of JSON formats, and if you want to store them locally, you can simply call json.stringify () to turn them into strings. Call json.parse () to convert the string to JSON format, as shown below:
var details = {author:"isaac"."description":"fresheggs"."rating":100};
storage.setItem("details",JSON.stringify(details));
details = JSON.parse(storage.getItem("details"));
Copy the code
IE8 supports JSON, but if you add the following compatibility mode code, you can switch to IE7 mode. Although window.localstorage is shown as [object] instead of [object Storage], getItem(), setItem(), etc.