HTML5 LocalStorage
The use of HTML5 in application development is increasing with each passing day and tech giants like Apple and Adobe are increasingly employing HTML5 developers for their application development process. localStorage is a client-side key-value database, meaning it is stored in the users browser. This means the users data is saved on their machine inside their browser. This also means that their data is only available to them when on that machine and in that browser. Remember that localStorage is per browser and not per computer. Where localStorage differs from cookies or sessionStorage is that the data stored in localStorage is still there even after the browser is closed and is shared across multiple windows. You don’t have to worry about a user deleting the cookies and all their data. Following is a simple example of using localStorage.
localStorage.setItem("name", "Hello World!"); //saves to the database, key/value
document.write(localStorage.getItem("name")); //Hello World!
localStorage.removeItem("name"); //deletes the matching item from the database
Line 1 saves a new entry in the local database with the key of ‘name’ and the value of ‘Hello World!’. That pair is now stored in your browsers database. Line 2 gets the item from the database with the key of ‘name’. In this case would then return ‘Hello World!’. In line 3 we remove the item from the database. Due to browser specific quotas you would want to check for exceptions so you would change line 1 above to the following.
try {
localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
To view this localStorage in Firefox, you would need to use the DOM area in Firebug and find ‘get localStorage’. Expanding this will show you the items in the database. If you’re using Safari or Chrome then you have a much better option. You are able to view these databases directly in the developer tools. Opening the Developer Tools you will notice the last item is Databases, clicking this will show you all databases, localStorage and sessionStorage info. You might also want to check to see if the user’s browser even supports localStorage and if it doesn’t we can warn them. Now the code above would look like this:
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
document.write(localStorage.getItem("name")); //Hello World!
localStorage.removeItem("name"); //deletes the matching item from the database
As you can see saving, retrieving and removing items from localStorage is pretty easy. Of course with just the above you can’t do a whole lot. Key-value storage might at first seem limited or even useless to some but with a little code you can accomplish a lot. In a future tutorial, we would add further functionality and create some useful applications.
Related articles:
- HTML5: Web Data Storage Methods
- Web Programming with SQL
- Document Type Declarations in HTML5
- HTML5: Latest Features – Part 2
- Creating Database Display with Razor
Comments
Web storage specifications
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:
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:
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:
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:
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.
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.
Related articles:
- HTML5: Web Data Storage Methods
- HTML5 LocalStorage
- HTML5: Latest Features – Part 2
- Managing web pages with ADO
- Storage and Transfer of Data with XML
Comments
You must log in to post a comment.
Web data storage methods
Posted by eTechy in Programming | 4 comments
Having discussed the basic differences between HTML5 and the previous versions of HTML, our main focus in this article would be discussing the data storage methods employed in HTML5. HTML5 maintains two basic methods for data storage: Permanent storage of data known as ‘localStorage’ and temporary storage of data for specific sessions known as ‘sessionStorage’. Previous versions of HTML did store data but that was done through cookies and two disadvantages govern data storage by cookies: First, cookies are unable to store large amount of data and second, data is stored with cookies with each request to the server. On the contrary, in HTML5, data is stored only when asked for, not with every subsequent request after establishing the connection with server.
The first method, the localStorage object stores the data with no time limit. The data will be available the next day, week, or year. For example, consider this piece of code:
<script type="text/javascript"> if (localStorage.pagecount) { localStorage.pagecount=Number(localStorage.pagecount) +1; } else { localStorage.pagecount=1; } document.write("Visits "+ localStorage.pagecount + " time(s)."); </script>In the above code, number of visitors to a certain web page are observed and stored. Since this count needs to be permanent and should remain intact after connection with server is lost, it is made permanent.
The second method, the sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. Consider the code below:
<script type="text/javascript"> if (sessionStorage.pagecount) { sessionStorage.pagecount=Number(sessionStorage.pagecount) +1; } else { sessionStorage.pagecount=1; } document.write("Visits "+sessionStorage.pagecount+" time(s) this session."); </script>The above code is used to store the number of times a specific user has visited a specific page during some particular sessions. After the connection is lost, that count is also lost since it was only for one session. Keeping in consideration the requirements of the developers and hosts, any of the above two methods can be utilized.