Common Browser Local Storage Methods
In daily development, you will inevitably encounter requirements for storing some data in the browser. Currently, the commonly used storage methods are:
cookie
Cookie was not originally designed for data storage, but rather to distinguish HTTP requests. That’s why every HTTP request carries cookies. If the amount of data stored in cookies is too large, it will certainly cause HTTP performance issues.
// set cookie (store data)
function setcookie(name,value,expired,path,domain){
var now=new Date();
if(name==null){
throw "Cookie Name Must not be Null";
}else if (value==null){
throw "Cookie Value Must not be Null";
}else if(expired==null){
expired=0;
}
if(path==null){
path="/";
}
if(domain==null){
domain=window.location.host;
}
now.setTime(now.getTime()+expired*1000);
document.cookie=name+"="+escape(value)+";expires="+now.toGMTString()+";path="+path+";domain="+domain;
}
// read cookie (read data)
function getcookie(name){
var allcookie=document.cookie;
thiscookie=allcookie.match(name+"=[^\\s]*");
mycookie=thiscookie[0].split("=");
a=mycookie[1].substring(0,mycookie[1].length-1);
return unescape(a);
}
localStorage
Compared to cookie operations, localStorage is much simpler. Additionally, every update to localStorage triggers an onstorage event.
localStorage.xxx="time-friend.com";
localStorage['xxx']="time-friend.com";
localStorage.setItem("xxx","time-friend.com");
// get
localStorage.xxx;
localStorage['xxx'];
localStorage.getItem("xxx");
// delete
localStorage.removeItem("xxx");
// clear localStorage
localStorage.clear();
// onstorage event
window.addEventListener("storage", function(){
// do whatever you want
}, false);
Flash ShareObject
This approach solves both of the drawbacks of cookie storage mentioned above, and it works across browsers. It should be considered the best local storage solution at the time. However, it requires inserting a Flash component into the page. Drawback: Requires the Flash plugin to be installed.
Google Gears
A local storage technology developed by Google. Drawback: Requires the Gears component to be installed.