Wednesday, 27 July 2016

Web Storage API : Local Storage


I am going to explain web storage API specially Local Storage today. Its just awesome.

There are three types of storage :

1) Session Storage : available for your websites only and valid till browser is open or reloads or restores/

2) Local Storage : available for your website only and valid while browser is closed and opened again.

3) There is global storage also which is accessed by all of the websites in your browser.

Testing for support vs availability :
Browsers which support localStorage will have a property with the window object named localStorage. But, for various reasons, just asserting that property exists may throw exceptions. so you might want to check it in a try catch so that it does not break the flow.

Like :
function storageAvailable(type) {
 try {
  var storage = window[type],
   x = '__storage_test__';
  storage.setItem(x, x);
  storage.removeItem(x);
  return true;
 }
 catch(e) {
  return false;
 }
}

Then you do a check and do your work.
if (storageAvailable('localStorage')) {
   var storage = window['localStorage'];
      storage.clear(); storage.setItems("test", "test");
}
else {
 // Too bad, no localStorage for us
}

And other things which you should keep in mind while working with local storage :
1) You can only store strings in the local storage. If you need to store objects use JSON.Stringify.
2) clear your local storage by clear() method.
3) When you put data into local storage by usingstorage.setItems("test", "test"), you should do it in a try catch as it can also give exception if not enough memory.
4) You can run the web storage test to find out how much memory you have with your browser.
Run Test for Storage
5) When you clear the history , it calls storage.clear(), something you can do in production environment.

No comments:

Post a Comment