Implementing Local Storage and Cross-Document Messaging - Advanced HTML5 - HTML5, 20 Lessons to Successful Web Development (2015)

HTML5, 20 Lessons to Successful Web Development (2015)


LESSON 17 Implementing Local Storage and Cross-Document Messaging


To view the accompanying video for this lesson, please visit

You are probably quite familiar with cookies: small units of data that are stored locally by your browser, which contain information helpful to using a website, such as your login details (to save you from continuously re-entering them), and which are often also used somewhat more intrusively to track your surfing habits.

Local storage is similar to cookies, but it supports storing much larger amounts of data and also supplies a local database engine to make saving and retrieving data much easier.

The benefits of this are more powerful web apps, with more data residing on your computer, rather than on servers somewhere else in the world. For example, a website that manages your TV viewing could store all your favorite programs in a local database, so that when you open the app, it only has to check a website of listings to see when these programs are on next, and on which channels. This takes a strain off the web server by leaving the data distributed among users.

Another benefit is that such local databases can be accessed from a local web page using JavaScript, meaning that the data can be used by the app even where there is no Internet connection (in this example case, as long as the TV listings have also been downloaded).

Using Local Storage

In the past the only way you could store data on a user’s computer was with cookies, which were limited in number and could hold only 4K each. They also have to be passed back on every page load or reload and, unless your server uses SSL (Secure Sockets Layer) encryption (like with HTTPS), each time a cookie is transmitted it travels in the clear.

But with HTML5 you have access to a much larger local storage space (typically between 5MB and 10MB per domain depending on the browser) that remains over page loads and between website visits (and even after powering a computer down and back up again), and which is not sent to the server on each page load.

You handle the data in pairs consisting of a key and its value. The key is the name assigned for referencing the data and the value can hold any type of data, but it is saved as a string.

All data is unique to the current domain. Any local storage created by websites with different domains is separate from the current local storage for security reasons, and is not accessible by any domain other than the one that stored the data.


For security reasons, local storage will work only when a web document is viewed after being sent via a web server. You cannot test documents that implement this feature from a local file system.

Storing and Retrieving Local Data

To access local storage, you use methods of the localStorage object such as setItem(), getItem(), removeItem(), and clear(). For example, to locally store a user’s username and password, you might use code such as this:


If the size of the value is larger than the disk quota remaining for the storage area, an “Out of memory” exception is thrown. Otherwise, when another page loads or when the user returns to the website, these details can be retrieved to save the user entering them again, like this:


If the key doesn’t exist, then the getItem() function returns a value of null.

You don’t have to use these function names if you don’t want to, because you can access the localStorage object directly as the two following statements are equivalent to each other:


And the two following statements are therefore also equivalent to each other:


Figure 17-1 shows an alert() message window displaying these values being retrieved from local storage, using the following code:




FIGURE 17-1 Data has been saved to and retrieved from local storage.

The first part of code within the if() statement writes an error message to the web page if local storage is not supported in the browser. This is determined by examining the localStorage object and, if it is undefined, then local storage is unavailable.

In the else part of the code, a message is first written to the web page indicating that local storage is supported. Then the username and password are saved to local storage with the setItem() function. Next, these values are retrieved from local storage into the variables username andpassword. Finally, an alert() message window is popped up, which displays the retrieved values.


Until they are erased, these values will remain in the local storage once saved, and you can verify this by trying the preceding code for yourself, running it once, commenting out the two lines of code that call setItem(), and then running it again—the alert window will still report the same values.

Removing and Clearing Local Data

To remove an item of data from the local storage, all you need to do is issue a command such as this:

username = localStorage.removeItem(’username’)

This serves to retrieve the item of data and place it into a variable (in this case username), and then deletes the data from local storage. If you don’t need to first read the data you are removing, you can simply call the function on its own, like this:


You can also completely clear the local storage for the current domain by issuing this command:



Try any of these methods on the preceding example and run it again, and you’ll find that the values have been erased.

Saving and retrieving data is starting to take us into the realms of much more complicated JavaScript programming, somewhat beyond the scope of this book. So the information in this lesson is mostly of use to programmers working with large amounts of JavaScript program code.

If you are a beginner to JavaScript, then it’s best to simply be aware of the possibilities of local storage, and come back here to refresh your memory about how it works when your programming is sufficiently advanced and you find the need for it.

Cross-Document Messaging

Cross-document messaging (also known as web messaging) allows scripts in different documents to interact with each other through use of the postMessage() function. The code to send messages is just a single instruction, in which you pass the message to be sent and the domain to which it applies, as follows:



In this example an <iframe> element with the ID of frame is created, that loads in the web document listen.htm (see the following code listing). Then, within the <script> section, the variable count is initialized to 1 and a repeating interval is set up to occur every second to post the string’Message ’ (using the postMessage() function) along with the current value of count, which is then incremented, and the message is posted only to listeners in the domain http://localhost.

The file listen.htm looks like this:


This example creates a <div> element with the ID output, in which the contents of received messages will be placed. In the <script> section there’s a single anonymous function attached to the onmessage event of the window. In this function the event .data property (the contents of the message) is then displayed, as shown in Figure 17-2.


FIGURE 17-2 The iframe is displaying messages from the parent frame.

For security reasons web messaging works only with domains, and so you cannot test it by loading files in from a file system—a web server must be used. The origin used in this example is http://localhost, because these examples are running on a local development server.

As it stands, the listen.htm document displays any and all messages it receives, which is also not very secure because malicious documents also present in the browser can attempt to send messages that unwary listener code might access. Therefore you can restrict the messages your listener reacts to using an if() statement to test the origin property, like this:



That concludes this part of the course on some of the more advanced aspects of HTML5 that you can use right now. In the next two lessons I’ll show you how to add HTML5 audio and video to your web pages, without having to resort to using plug-ins such as Microsoft Silverlight or Adobe Flash.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in the appendix.

1. Why is local storage a better solution than cookies?

2. How can you determine whether local storage is available in a browser?

3. How do you store an item of local storage data?

4. How do you retrieve an item of local storage data?

5. How can you remove an item from local storage?

6. How do you clear all the data relating to your domain in local storage?

7. How can you post a message to another document loaded into the browser?

8. How can you listen for messages from other loaded documents?

9. What should you do to ensure that you post messages only to the documents you want to receive them?

10. What should you do to ignore any message received from documents from which you do not wish to receive them?