Chrome Extensions

Article: Using HTML 5 Local Storage in Chrome Extensions

Rajdeep Dua
December 2009

Goal

This article outlines how chrome extensions can leverage HTML 5 local storage feature to persist data across popup and browser sessions. It uses a sample extension which is already available in the Extension Gallery. This article is limited to structured storage and retrieval from local storage. SQL support and web storage is out of scope for this article.

Prerequisites

Before you read this article, you should already be familiar with:

Index

This tutorial is divided into the following sections:

  1. Setting up the Sample Extension
  2. Extension Use cases
  3. Understanding HTML 5 Local Storage APIs in Chrome
  4. Underlying implementation in the browser - optional
  5. Source Code
  6. Summary

Setting up and running the Sample Extension

  1. Install the extension from the extension gallery
    Extension is available at the following URL : https://chrome.google.com/extensions/detail/hmbpgbeiphknbkjjfppodijapijlpkkc
  2. Click on the Extension Browser Action
  3. Extension will show last three names entered in the popup
  4. Enter a new name and see the names change
  5. Close the popup or the browser, the Names are still retrieved beyond the lifecycle of the session or the browser instance

The objective of this sample is to:

Show usage of HTML 5 Local Storage APIs within the extension

img1

Figure 1: Sample popup screen when user clicks on the browser action

Figure 1 shows the popup.html before user interaction starts.

All the interaction with the Local Storage takes place through background.html. Figure 2 elaborates how this interaction looks like,

Architecture

Figure 2 : Interaction between Popup page, backogrund page and Chrome's Local Storage

Extension Use Cases

image2

User enters first name

1. User enters a name

2. Clicks on store button

3. 'jane' is stored int he local storage and updated as Last Value stored 1

 

image3

User enters second name

4. Users enters 'adam'

5.Presses store button, 'adam' is stored in local storage

6. 'adam' is updated as last value stored 1

7. jane is moved from last value 1 to Last Value 2

image4

Use enters third name

8. User enters 'george'

9.Presses store button, value is stored in local storage

10. 'george' becomes Last Value stored 1

11,12 : Previously stored values are moved as shown in the figure

 

Continue reading Section 3 to learn how the example code works.

Understanding HTML 5 Local Storage APIs in Chrome Browser

In this section, we will explain how the LocalStorage APIs are being used. Local Storage provides ability to store keys and values which could be retrieved across browser sessions. Pasted below is the JavaScript from background.html
  //sets the item in the localstorage
  function setItem(key, value) {
    try {
      log("Inside setItem:" + key + ":" + value);
      window.localStorage.removeItem(key);
      window.localStorage.setItem(key, value);
    }catch(e) {
      log("Error inside setItem");
      log(e);
    }
    log("Return from setItem" + key + ":" +  value);
  }
  //Gets the item from local storage with the specified
  //key
  function getItem(key) {
    var value;
    log('Get Item:' + key);
    try {
      value = window.localStorage.getItem(key);
    }catch(e) {
      log("Error inside getItem() for key:" + key);
	  log(e);
	  value = "null";
    }
    log("Returning value: " + value);
    return value;
  }
  //Clears all the key value pairs in the local storage
  function clearStrg() {
    log('about to clear local storage');
    window.localStorage.clear();
    log('cleared');
  }

  function log(txt) {
    if(logging) {
      console.log(txt);
    }
  }

Here are some comments on the relevant parts:

  window.localStorage.removeItem(key);    //remove item with the specified key
  window.localStorage.setItem(key, value);//set item with the key value pair
  window.localStorage.getItem(key);       //get item for the specific key
  window.localStorage.clear();            //clear all the items from the storage

HTML 5 Local Storage specification lays out the following syntax for the local storage. As can be seen the syntax is fully compliant. Section below shows the IDL syntax from the HTML5 web storage spec.

interface Storage 
{
  readonly attribute unsigned long length;
  getter DOMString key(in unsigned long index);    
  getter any getItem(in DOMString key);    
  setter creator void setItem(in DOMString key, in any data);    
  deleter void removeItem(in DOMString key);    
  void clear();  
}; 

Implementation in the Chrome browser

Note : This is an optional section, only for understanding purpose.

Chrome uses the underlying implementaiton in the webkit to provide support for Local Storage. Renderer's render process interacts with the webkit storage area using the WebKit APIs to store, get and clear the specified key value pairs

Architecture3

Figure 3 : Main components of Chrome browser and their interaction with the web storage

Section below shows the webkit C++ APIs which are used for this retrieval.


namespace WebKit {
class WebString; // In WebCore, there's one distinct StorageArea per origin per StorageNamespace. This // class wraps a StorageArea. All the methods have obvious connections to the spec: // http://dev.w3.org/html5/webstorage/ class WebStorageArea { public: virtual ~WebStorageArea() { }

// The number of key/value pairs in the storage area. virtual unsigned length() = 0;

// Get a value for a specific key. Valid key indices are 0 through length() - 1. // Indexes may change on any set/removeItem call. Will return null if the index // provided is out of range. virtual WebString key(unsigned index) = 0;

// Get the value that corresponds to a specific key. This returns null if there is // no entry for that key. virtual WebString getItem(const WebString& key) = 0;

// Set the value that corresponds to a specific key. QuotaException is set if we've //the StorageArea would have exceeded its quota. The value is NOT set when there's
//an exception.
virtual void setItem(const WebString& key, const WebString& value, bool& quotaException) = 0;

// Remove the value associated with a particular key. virtual void removeItem(const WebString& key) = 0;

// Clear all key/value pairs. virtual void clear() = 0; };

} // namespace WebKit

Source Code

Please download the source code from the following location.

sample-local-storage.zip

Summary

Local Storage APIs, also called Web Storage APIs are an easy and convenient mechanism to store and re-use user choices and responses or some other data across the browser sessions. This article and the associated sample demonstrates how easy it is to use this feature in chrome extensions.

References