SlideShare a Scribd company logo
1 of 3
Download to read offline
Articles from Jinal Desai .NET
APIs in HTML5
2012-12-29 19:12:54 Jinal Desai

Storage APIs in HTML5

Storage APIs are HTML5 answers to browser cookies limitations. These APIs allows
developers to store some basic information and values that can be user specific
and tame cookies limitations like it’s length, number of cookies per website and
many more. Typical examples of such information are saving game state, saving
navigation locations, etc. The size restriction of storing data using Storage APIs is
around 5MB. This limit is suggested by W3C, but the specs provide some room for
implementation details. So actual size depends on browser, but it does not fluctuate
that much.

Local Storage
It is basic implementation of storing data locally on user’s machine. It is a key/value
pair collection. It is window.localStorage. It allows application to run offline with some
data stored on user’s machine like user’s name and preferences.

You can use localStorage object without window. Like you can use it directly as
localStorage instead of window.localStorage. However, it is better code practice to
use window.localStorage.

To check browser is supporting window.localStorage or not you can use following
function.
function isLocalStorageAvailable() {
   try {
      return 'localStorage' in window &&
             window['localStorage']!==null;
   }
   catch(err) {
      return false;
   }
}

Storing value in localStorage is very easy with it’s setItem function.

if(isLocalStorageAvailable) {
   window.localStorage.setItem("Name","Jinal Desai");
}

To get it back use getItem function of localStorage.

if(isLocalStorageAvailable) {
   var Name = window.localStorage.getItem("Name");
}

How to clear it? To clear all the data stored in the localStorage API use clear
function.
if(isLocalStorageAvailable) {
   window.localStorage.clear();
}

To remove only particular item from localStorage you can use it’s removeItem
function.

if(isLocalStorageAvailable) {
   window.localStorage.removeItem("Name");
}

Session Storage
The window.sessionStorage stores information for a single session only. The
information is lost when the user ends the session. All the functionality is same as
window.localStorage you just need to replace sessionStorage instead of
localStorage in all above examples.

Difference between Local Storage and Session Storage
The main difference is that localStorage persists information over different tabs or
windows, even if we close the browser according to the domain’s security policy
user’s choice about quota limit.

While with sessionStorage when HTML document is created, the user agent must
see to check if document’s top level browsing context has allocated a session
storage area for that document’s origin. If it has not, a new storage area for that
document’s origin must be created. So each document object has separate object
for it’s windows sessionStorage attribute. In summary, the sessionStorage object
does not persists if we close the tab/window or it does not exists if we access the
stored value via different tab/window.

AppCache API in HTNL5
In some scenarios storing user’s information in bits and pieces is not enough. You
need to store much more data so that entire application can work offline. HTML5 has
provided caching functionality so that you can cache entire file/files. So when user is
offline browser can access cached resources.

Cached resources are local thus it loads faster, it reduces server load and also
supports browsing without internet connection. AppCache API is maintaining
manifest file(.mf) for keeping track of cached pages. To enable cache, include
manifest attribute on documents html tag.
<html manifest="http://jinaldesai.net/manifest.mf">
...
</html>

Once you include manifest attribute on html document, it will automatically cache
entire html page.

Following is example of typical manifest file. The paths of all the files caches are
relative.

//Manifest file start here.
CACHE MANIFEST //Every manifest file starts with CACHE MANIFEST

NETWORK: //Network files are never cached.
share_Prices.php

FALLBACK: //Files that wasn’t cached or wasn’t save correctly
//and need to give message to user.
message_Offline.html

CACHE: //Actual cached resource.
index.html
style.css
images/logo.png
//Manifest file ends here.

To know cache status use following code.

var applicationCache = window.applicationCache;
applicationCache.status === applicationCache.UNCACHED
applicationCache.status === applicationCache.IDLE
applicationCache.status === applicationCache.CHECKING
applicationCache.status === applicationCache.DOWNLOADING
applicationCache.status === applicationCache.UPDATEREADY
applicationCache.status === applicationCache.OBSOLETE

To update cache.
var applicationCache = window.applicationCache;
applicationCache.update(); //Update user's cache
if(applicationCache.status == window.applicationCache.UPDATEREADY) {
   applicationCache.swapCache();
   //swap updated user's cache with old stored cache
}

Events in AppCache API
applicationCache.addEventListener('cached', handleCacheEvent, false);
//first time cache
applicationCache.addEventListener('checking', handleCacheEvent, false);
//checking for update
applicationCache.addEventListener('downloading', handleCacheEvent, false);
//update is available and browser is downloading update
applicationCache.addEventListener('error', handleCacheError, false);
//404 or 410, downloading failed or manifest changed
//when download in progress
applicationCache.addEventListener('noupdate', handleCacheEvent, false);
//first download
applicationCache.addEventListener('obsolete', handleCacheEvent, false);
//4040 or 410, cache being deleted
applicationCache.addEventListener('progress', handleCacheEvent, false);
//cache being fetched
applicationCache.addEventListener('updateready', handleCacheEvent, false);
//when manifest newly downloaded

Conclusion
As browser and user experiences is eveolving, HTML5 has evolved to store
information locally at user’s machine. You can use localStorage or sessionStorage
to store name/value pairs of user/application specific values or you can cache
multipages to let your user work offline.

More Related Content

Recently uploaded

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

APIs in HTML5 at Jinal Desai .NET

  • 1. Articles from Jinal Desai .NET APIs in HTML5 2012-12-29 19:12:54 Jinal Desai Storage APIs in HTML5 Storage APIs are HTML5 answers to browser cookies limitations. These APIs allows developers to store some basic information and values that can be user specific and tame cookies limitations like it’s length, number of cookies per website and many more. Typical examples of such information are saving game state, saving navigation locations, etc. The size restriction of storing data using Storage APIs is around 5MB. This limit is suggested by W3C, but the specs provide some room for implementation details. So actual size depends on browser, but it does not fluctuate that much. Local Storage It is basic implementation of storing data locally on user’s machine. It is a key/value pair collection. It is window.localStorage. It allows application to run offline with some data stored on user’s machine like user’s name and preferences. You can use localStorage object without window. Like you can use it directly as localStorage instead of window.localStorage. However, it is better code practice to use window.localStorage. To check browser is supporting window.localStorage or not you can use following function. function isLocalStorageAvailable() { try { return 'localStorage' in window && window['localStorage']!==null; } catch(err) { return false; } } Storing value in localStorage is very easy with it’s setItem function. if(isLocalStorageAvailable) { window.localStorage.setItem("Name","Jinal Desai"); } To get it back use getItem function of localStorage. if(isLocalStorageAvailable) { var Name = window.localStorage.getItem("Name"); } How to clear it? To clear all the data stored in the localStorage API use clear function. if(isLocalStorageAvailable) { window.localStorage.clear(); } To remove only particular item from localStorage you can use it’s removeItem
  • 2. function. if(isLocalStorageAvailable) { window.localStorage.removeItem("Name"); } Session Storage The window.sessionStorage stores information for a single session only. The information is lost when the user ends the session. All the functionality is same as window.localStorage you just need to replace sessionStorage instead of localStorage in all above examples. Difference between Local Storage and Session Storage The main difference is that localStorage persists information over different tabs or windows, even if we close the browser according to the domain’s security policy user’s choice about quota limit. While with sessionStorage when HTML document is created, the user agent must see to check if document’s top level browsing context has allocated a session storage area for that document’s origin. If it has not, a new storage area for that document’s origin must be created. So each document object has separate object for it’s windows sessionStorage attribute. In summary, the sessionStorage object does not persists if we close the tab/window or it does not exists if we access the stored value via different tab/window. AppCache API in HTNL5 In some scenarios storing user’s information in bits and pieces is not enough. You need to store much more data so that entire application can work offline. HTML5 has provided caching functionality so that you can cache entire file/files. So when user is offline browser can access cached resources. Cached resources are local thus it loads faster, it reduces server load and also supports browsing without internet connection. AppCache API is maintaining manifest file(.mf) for keeping track of cached pages. To enable cache, include manifest attribute on documents html tag. <html manifest="http://jinaldesai.net/manifest.mf"> ... </html> Once you include manifest attribute on html document, it will automatically cache entire html page. Following is example of typical manifest file. The paths of all the files caches are relative. //Manifest file start here. CACHE MANIFEST //Every manifest file starts with CACHE MANIFEST NETWORK: //Network files are never cached. share_Prices.php FALLBACK: //Files that wasn’t cached or wasn’t save correctly //and need to give message to user. message_Offline.html CACHE: //Actual cached resource. index.html style.css images/logo.png
  • 3. //Manifest file ends here. To know cache status use following code. var applicationCache = window.applicationCache; applicationCache.status === applicationCache.UNCACHED applicationCache.status === applicationCache.IDLE applicationCache.status === applicationCache.CHECKING applicationCache.status === applicationCache.DOWNLOADING applicationCache.status === applicationCache.UPDATEREADY applicationCache.status === applicationCache.OBSOLETE To update cache. var applicationCache = window.applicationCache; applicationCache.update(); //Update user's cache if(applicationCache.status == window.applicationCache.UPDATEREADY) { applicationCache.swapCache(); //swap updated user's cache with old stored cache } Events in AppCache API applicationCache.addEventListener('cached', handleCacheEvent, false); //first time cache applicationCache.addEventListener('checking', handleCacheEvent, false); //checking for update applicationCache.addEventListener('downloading', handleCacheEvent, false); //update is available and browser is downloading update applicationCache.addEventListener('error', handleCacheError, false); //404 or 410, downloading failed or manifest changed //when download in progress applicationCache.addEventListener('noupdate', handleCacheEvent, false); //first download applicationCache.addEventListener('obsolete', handleCacheEvent, false); //4040 or 410, cache being deleted applicationCache.addEventListener('progress', handleCacheEvent, false); //cache being fetched applicationCache.addEventListener('updateready', handleCacheEvent, false); //when manifest newly downloaded Conclusion As browser and user experiences is eveolving, HTML5 has evolved to store information locally at user’s machine. You can use localStorage or sessionStorage to store name/value pairs of user/application specific values or you can cache multipages to let your user work offline.