Next page | Contents page |

Local storage

Version 5 of HTML introduced a new way of storing data between sessions, held somewhere on the client system by the browser but only accessible by a program from the same origin (domain, or local file directory in our case). This is superior to cookies in several ways. The amount of data that can be stored is much larger than was allowed in cookies and the storage should be more secure. There is also a corresponding way of storing data on a web server, but this course has only been about local (client) programs so we will not go into server storage.

The data are stored as JSON strings, which is why they were introduced on the previous page. Each such string is identified by a key that can be used to retrieve it again.

HTML5 added property localStorage to the window object. So to store some data (typically an object structure, as we saw on the previous page):

localStorage.setItem ("myKey", JSON.stringify (myObject));

And later (maybe in a different session) the data can be retrieved:

var myString = JSON.parse (localStorage.getItem ("myKey"));

Note that the retrieved string is an object literal. If you need to recreate objects of particular types that you have programmed then there will be a need to analyse the string and call the relevant object constructors. In practice this is not as difficult as it sounds, it just needs some careful thought.

Data entries can also be deleted from storage:

localStorage.removeItem ("myKey");

As always, more detail can be found on Mozilla's reference page.

Next page | Contents page |