Working with local web storage

The use of local web storage is easy with HTML 5, since it provides a number of APIs to interact with the web storage. So, without wasting much time, let's take a look at a simple example of how we can use local web storage. For this, we will create a simple JavaScript file known as localstore.js with the following contents:

// check if the localStorage is supported by the browser or not
if(localStorage) {
// Put some contents inside the local storage
localStorage.setItem("username", "joe_henry");
localStorage.setItem("uid", "28372");

// Retrieve some contents from the local storage
var user_email = localStorage.getItem("user_email");
} else {
alert("The browser does not support local web storage");
}

This was a very simple example of how to use the local webstorage API provided by HTML 5 in a compatible browser. Let's spend some time understanding what we did in the script:

At the start of the script, we first checked if the browser supports the HTML 5 local storage API or not; in case it does not support the local storage API, we just display an alert showing the unavailability of the feature. If the browser supports the API, we move on to using some simple localStorage APIs to store and retrieve some content from the local web storage. The setItem(key, value) method allows for storing a new key value pair inside the storage, or using the getItem(key) method, which allows us to retrieve the content of the key from the web storage.

Now, we have a little bit of an idea about the local storage API and how we can use it to store some data that we can access any time without worrying about the state of the session. But what if we wanted to store some data up until the point where the user's browser session was valid? For this, the HTML 5 web storage API provides a session storage mechanism, which provides similar methods as local storage but stores the data only until a user session is valid. Let's take a look at how we can use the session store to store data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.61.218