MENU
Local Storage & Session Storage
Like a cookie, a localStorage variable remains on the visitor's computer after the browser window is closed. Unlike a cookie, it is not sent to the server and does not expire. It can only be accessed by the web page that stores it.Only used when asked for, it can store a large amount of data without affecting the performance.
A sessionStorage variable is like a localStorage variable, except that it is deleted when the visitor closes the browser window or tab.
Here 'test' is an arbitrarily defined property, and can only be assigned a string value. When the page first loads, localStorage.test and sessionStorage.test are undefined. As the user refreshes the page, the browser shows the detection messages.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
if(Storage){
document.write(localStorage.test);
localStorage.test="Local Storage Detected. ";
document.write(sessionStorage.getItem('test'));
sessionStorage.setItem('test', "Session Storage Detected.");
} else {
document.write("Sorry, your browser does not support web storage...");
}
</script></body></html>
To remove an item:
localStorage.removeItem("myItem");
To remove all items:
localStorage.clear();
To store an image into localStorage, convert the image data to a base-64 string first:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
To store any kind of file, consider using FileReader and Blob:
var rhinoStorage = localStorage.getItem("rhino"),
rhino = document.getElementById("rhino");
if (rhinoStorage) {
rhino.setAttribute("src", rhinoStorage);
} else {
var xhr = new XMLHttpRequest(),
blob,
fileReader = new FileReader();
xhr.open("GET", "rhino.png", true);
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
blob = new Blob([xhr.response], {type: "image/png"});
fileReader.onload = function (evt) {
var result = evt.target.result;
rhino.setAttribute("src", result);
localStorage.setItem("rhino", result);
};
fileReader.readAsDataURL(blob);
}
}, false);
xhr.send();
}