Local storage over the internet is supported by most of the modern browsers. This local storage provides functionality similar to that of cookies, but it is different from cookies to some extent. In a sense, the storage provided by this method is much more refined and better compared to simple cookie storage. In this method, data stored in a browser would only be deleted from the local machine when requested to do so by the user. Generally, a browser will always avoid deleting data while a script that could access that data is running. Web browsers expose Web Storage through the localStorage object in JavaScript. One easy way to determine whether a Web Browser can support Web Storage is to execute this JavaScript code:
1 |
var webStorageSupported = ('localStorage' in window) && window['localStorage'] !== null; |
There is a certain set of methods that is implemented by local storage to undertake the task of data storage. Important methods and properties are discussed below:
1 2 3 4 5 6 7 8 |
interface Storage { readonly long <strong>length</strong>; void <strong>setItem(String key, Object data)</strong>; Object <strong>getItem(String key)</strong>; void <strong>removeItem(String key)</strong>; void <strong>clear()</strong>; String <strong>key(long index)</strong>; }; |
The length property is very useful. It will return the number of key/value pairs currently saved to Local Storage under the currently accessed domain:
1 |
alert(localStorage.length); |
In case there isn’t any keyword previously stored in the local storage, then the above script will display an alert window with “0″ as the message, otherwise the message will be the number of persisted key/value pairs.
Another important method is setItem(key, value)which saves a new entry on the local machine. For this purpose, following code is executed:
1 |
localStorage.setItem('name', 'arman'); |
We also have another noteworthy method named getItem(key) whose purpose is to ensure that key name (in the above script) was truly saved to the local storage with the value arman.
1 2 3 |
localStorage.setItem('name', 'arman'); var value = localStorage.getItem('name'); alert(value); |
There are a lot of other important methods used in local storage to provide much more efficient storage compared to cookies. Some of the further methods and properties would be discussed in a future tutorial.