Web Storage


Web Storage takes the principles of older storage mechanisms such as cookies, and makes them more powerful and flexible.
With this you can store information in the browser for users to continue working when offline.

Why use Web Storage instead of Web SQL?
Web storage is supported on 91.9% of browsers where Web SQL is only supported on 46.39%
Though Web SQL allows much more functionality, due to the lack of support on browsers I can not use it.
To see the breakdown of which browsers are supported:
Web Storage stats: http://caniuse.com/namevalue-storage
Web SQL database stats: http://caniuse.com/sql-storage

This example uses Web Storage to make a simple listing web app where you can add and remove items from the list in offline mode.

I will be using localStorage which stores the data with no expiration date, so even if the browers is closed down it will be available again next time it is opened.
sessionStorage is also available but will lose all data when the browser is closed so is not used in my example.

Amount of data you can store:

2.5 MB per origin in Google Chrome
5 MB per origin in Mozilla Firefox
5 MB per origin in Opera
10 MB per storage area in Internet Explorer

Storage size can be customized by the user so this is not guranteed.

Working demo available at: http://glynrob.com/webapp/webstorage/
Working code example available at https://github.com/glynrob/webstorage

Files required:
add_small.png // add icon (stolen from google)
default.css // css for the html
icon_delete_small.png // delete icon (stolen from google)
index.html // html for the content of the page
jquery-1.7.2.min.js // jquery library
json2.js // json javascript library
wsdemo.manifest // manifest file

Application Cache:

For an offline web app you will also need to use Application Cache to store any images, css, javascript and html files so they can be used offline.

This is very simple and only requires 1 additional file and 1 html update.

Manifest file:
wsdemo.manifest
This lists all resources needed to be available when offline so the browser caches them locally on the device.

CACHE MANIFEST
# Place all files below that need to be saved offline
CACHE:
index.html
default.css
add_small.png
icon_delete_small.png
jquery-1.7.2.min.js
json2.js

HTML code
index.html
Just adding the manifest location into the html tag calls this file to cache the resources

<!DOCTYPE html>
<html manifest="wsdemo.manifest">
<head>
<meta name="viewport" content="width=device-width">

This may request the user to allow offline storage when they visit this page which they can allow.
If the user does not allow this Web storage will still work, just the pretty images and CSS won’t be present when working offline.

I also added a viewport to keep the pages width the full width of the device.

Web storage:

Pull data from the storage

window.addEventListener("DOMContentLoaded", loadSavedData, false);// load locally saved data when the page opens
  
	// get the locally saved data
	function loadSavedData(){
		savedData = localStorage.getItem("data"); // get data from local storage
		if (savedData && savedData != null) { // if not empty
			savedData = JSON.parse(savedData); // get data from returned json string
			savedData = savedData['dataToSave']; // set savedData from dataToSave item
			
			showListItems();// Generate the list items and display
			showLocalData();// show data
		} else {
			savedData = [];
		}
	}	

This pulls the data from the localStorage and places it into a variable.
I then use JSON.parse to break out the data into a JSON array as this is how I want the data
Finally run a couple of functions to display out the list html

Add data to the storage

This function gets the object passed to it, uses JSON.stringify to make the result a string.
Then stores that string using localStorage.setItem(“data”, cleanData);
Finally I run a couple of functions to regenerate the list html

Detecting if in Online or Offine mode:

You can go further and store the information on a server if online, and store the data locally if offline to be synced at a later date if you wish.
To detect if the browser is online is very simple with navigator.onLine returning true or false.
My example just updates the html stating if they are online or not.

// display if they are online or not
  	if (!navigator.onLine){
			$('#status').html('Offline');
		} else {
			$('#status').html('Online');
		}

So this is a start to a web app that can behave like a native app on mobile devices.

Hope this help those starting to use these features

Leave a Reply

Your email address will not be published. Required fields are marked *