Tutorial HTML5 Local Storage

We will learn about HTML5 local storage in this tutorial. Local storage is newer technology that can used instead of cookies for storing web app data in user’s browser. But unlike cookies, its data is not sent back to the server on each request.

Data from 2MB to 10MB is stored on local computer and is browser and machine specific. “local storage” persist across sessions and machine restarts. “session storage” only persists during that browsing session. Depending on the browser, local storage will not work or not persist across sessions if incognito or private mode is used.

Data is stored in key value pairs and always as strings. But you can use parseInt(), JSON.parse() and JSON.stringify() to convert.

Let’s create a webpage that asks for user name and store that in local storage. …

The next time you return even after you close your browser or shut down your machine, it will know your name and display your name. We start with the following HTML

Setting Local Storage

The script at the bottom detects if local storage is supported by using the function localStorageSupported() from the Sitepoint article “An Overview of the web storage API“.

Now when button is clicked, we get the value of the input box and store that value to local storage under the key of “username”…

We wrapped it in a try catch block in case something goes wrong such as exceeding quota, etc.

Note that the following are also equivalent statement for saving to local storage…