HTML5

HTML5 Offline Storage Example

The aim of this article is to go through HTML5 local storage, also referred to as ‘offline’ storage. When web developers think of storing anything about the user, they immediately think of uploading to the server. HTML5 changes that, as there are now several technologies allowing the app to save data on the client device. It might also be sync’d back to the server, or it might only ever stay on the client: that’s down to you, the developer.

1. What is HTML Local Storage?

With local storage, web applications can store data locally within the user’s browser. Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Local storage is per domain. All pages, from one domain, can store and access the same data.

2. Browser Support

The following table shows the browser version in which full support of the feature is available.

HTML5 Offline Storage Browser Support
HTML5 Offline Storage Browser Support

3. Why use Client-Side Storage?

There are several reasons to use client-side storage.

• First, you can make your app work when the user is offline, possibly sync’ing data back once the network is reconnected.

• Second, it’s a performance booster; you can show a large corpus of data as soon as the user clicks on to your site, instead of waiting for it to download again.

• Third, it’s an easier programming model, with no server infrastructure required. Of course, the data is more vulnerable and the user can’t access it from multiple clients, so you should only use it for non-critical data, in particular cached versions of data that’s also “in the cloud”.

4. Offline Technologies

• Web Storage simply provides a key-value mapping, e.g. localStorage[“name”] = username;. Unfortunately, present implementations only support string-to-string mappings, so you need to serialise and de-serialise other data structures. You can do so using JSON.stringify() and JSON.parse().

• Web SQL Database gives you all the power – and effort – of a structured SQL relational database.

• Indexed Database is somewhere in between Web Storage and Web SQL Database. Like Web Storage, it’s a straightforward key-value mapping, but it supports indexes like those of relational databases, so searching objects matching a particular field is fast; you don’t have to manually iterate through every object in the store.

• File Access is an API for reading file content in JavaScript. Given a set of files the user has added to a “file” input element, you can read the content of the file or reference it as a URL, e.g. if the user has specified an image file, you can show the image. There are also proposals underway for file writing capabilities.

5. HTML Local Storage Objects

HTML local storage provides two objects for storing data on the client:

window.localStorage – stores data with no expiration date
window.sessionStorage – stores data for one session (data is lost when the browser tab is closed)

Before using local storage, check browser support for localStorage and sessionStorage:

if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Web Storage support not present.
}

5.1 The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname"); 

The detailed snippet for this would be:

// Check browser support if (typeof(Storage) != "undefined") { // Store localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname"); } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage..."; }

So because we retrieved the last name, that we predefined, we’d just get Smith in the browser:

Local Storage Object
Local Storage Object

Let’s go a bit further into the explanation of this example. So what we did was:
1. Create a localStorage name/value pair with name=”lastname” and value=”Smith”
2. Retrieve the value of “lastname” and insert it into the element with id=”result”

We could also have written the example above like this:

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

The syntax for removing the “lastname” localStorage item is as follows:

localStorage.removeItem("lastname");

Note that name/value pairs are always stored as strings. Remember to convert them to another format when needed!

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

if (localStorage.clickcount) {
    localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
    localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

By setting up a simple HTML to show a button where we click and some elements appear telling us the number of times we’ve clicked we’d see the desired result:

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
            localStorage.clickcount = Number(localStorage.clickcount)+1;
        } else {
            localStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}

Click the button to see the counter increase.

Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).

THe initial view of the HTMl would be this:

Counting the Number of Clicks (Part I)
Counting the Number of Clicks (Part I)

Now if we click, say, for example, 14 times on that button, we’d get a nice message notifying us about that number of clicks.

Counting the Number of Clicks (Part II)
Counting the Number of Clicks (Part II)

5.2 The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

The following example counts the number of times a user has clicked a button, in the current session:

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session."; 

The full snippet for this example would be this:

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.clickcount) {
            sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
        } else {
            sessionStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}

Click the button to see the counter increase.

Close the browser tab (or window), and try again, and the counter is reset.

So if we closed the tab after some clicks, and then reopened, we’d see the count of clicks starts from 0, because the last session storage was deleted!

The sessionStorage Object
The sessionStorage Object

6. Conclusion

Offline storage has many potential applications, well beyond the obvious “I want my application to run when users are on a plane” scenario. Developers in the past had to resort to workarounds, plugins, or browser-specific APIs, but modern developers have a veritable arsenal of standards-based capabilities to leverage. The challenge is to decide which to use when, and to use them in the right way.

7. Download

Download
You can download the full source code of this example here: HTML5 Offline Storage

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
lous
lous
8 years ago

How do you do so that the text “You have clicked the button time(s) in this session.”
will always appear without clicking the button first? I want it to show the number always without needing to click the button for the text to appear.

Back to top button