English | Site Directory

Google Gears API

LocalServer API

The LocalServer module allows a web application to cache and serve its HTTP resources locally, without a network connection.

Contents

  1. Overview
  2. Example
  3. Classes
    1. LocalServer
    2. ManagedResourceStore
    3. ResourceStore
    4. FileSubmitter
  4. Manifest file
  5. Cookies and the LocalServer
  6. Location of cached files

Overview

The LocalServer module is a specialized URL cache that the web application controls. Requests for URLs in the LocalServer's cache are intercepted and served locally from the user's disk.

Resource stores

A resource store is a container of URLs. Using the LocalServer module, applications can create any number of resource stores, and a resource store can contain any number of URLs.

There are two types of resource stores:

  • ResourceStore - for capturing ad-hoc URLs using JavaScript. The ResourceStore allows an application to capture user data files that need to be addressed with a URL, such as a PDF file or an image.
  • ManagedResourceStore - for capturing a related set of URLs that are declared in a manifest file, and are updated automatically. The ManagedResourceStore allows the set of resources needed to run a web application to be captured.

For both types of stores, the set of URLs captured is explicitly controlled by the web application.

Updating of cached resources

A key difference between the two types of stores is how resources are updated. The contents of a ManagedResourceStore are automatically updated whenever the version string in the store's manifest file changes. The ResourceStore's contents are never automatically updated, and are only updated explicitly by the application.

Google Gears automatically updates ManagedResourceStores according to these rules:

  • checkForUpdate() is called each time a resource contained in a ManagedResourceStore is requested and served locally, but no more often than once every 10 seconds.
  • If the manifest file's version value has changed, the automatic update process runs. For further details, see checkForUpdate.

Local serving of cached resources

The LocalServer intercepts HTTP/HTTPS requests and serves them from the cache when all of these conditions are met:

  • The URL is cached in a ResourceStore or ManagedResourceStore,
  • The resource store's enabled attribute is set to true, and
  • If the resource store has a requiredCookie attribute, the request must have a cookie that matches. For further details read Cookies and the LocalServer.

The LocalServer always serves a cached resource when the conditions are met, regardless of the network connection. The URLs contained in a store are eligible for local serving without requiring the application to open the store.

To disable local serving of stored resources and force URLs to be served using the regular network connection, the application can set the store's enabled attribute to false.

 

Example

<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript">
var localServer = google.gears.factory.create('beta.localserver');
var store = localServer.createManagedStore('test-store');
store.manifestUrl = 'site-manifest.txt';
store.checkForUpdate();
</script>
// site-manifest.txt
{
  "betaManifestVersion": 1,
  "version": "site_version_string",
  "entries": [
    { "url": "site.html" },
    { "url": "gears_init.js" }
  ]
}

Classes

LocalServer class
   boolean              canServeLocally(string url)
   ResourceStore        createStore(string name, [string requiredCookie])
   ResourceStore        openStore(string name, [string requiredCookie])
   void                 removeStore(string name, [string requiredCookie])
   ManagedResourceStore createManagedStore(string name, [string requiredCookie])
   ManagedResourceStore openManagedStore(string name, [string requiredCookie])
   void                 removeManagedStore(string name, [string requiredCookie])
ManagedResourceStore class
   readonly  attribute string  name
   readonly  attribute string  requiredCookie
   readwrite attribute boolean enabled
   readwrite attribute string  manifestUrl
   readonly  attribute int     lastUpdateCheckTime
   readonly  attribute int     updateStatus
   readonly  attribute string  lastErrorMessage
   readonly  attribute string  currentVersion
   void checkForUpdate()
ResourceStore class
   readonly  attribute string  name
   readonly  attribute string  requiredCookie
   readwrite attribute boolean enabled
   int           capture(string urlOrUrlArray, completionCallback)
   void          abortCapture(int captureId)
   void          remove(string url)
   void          rename(string srcUrl, string destUrl)
   void          copy(string srcUrl, string destUrl)
   boolean       isCaptured(string url)
   void          captureFile(fileInputElement, url)
   string        getCapturedFileName(url)
   string        getHeader(string url, string name)
   string        getAllHeaders(string url)
   FileSubmitter createFileSubmitter()
FileSubmitter class
   void      setFileInputElement(htmlElement el, string url)


LocalServer class

The LocalServer is a factory and container for the set of ResourceStores and ManagedResourceStores your application creates and uses. Use resource stores to enable your JavaScript application to execute without a network connection.

To create a LocalServer object, use the Gears Factory as follows:

<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript">
var localServer = google.gears.factory.create('beta.localserver');
</script>

Methods

canServeLocally(string url)
Return Value boolean
Parameters url - relative or absolute URL that is from the same origin as the current page
Exceptions Throws an exception if the URL is not from the same origin as the current page.
Description Returns true if a request for the URL can be satisfied from any of the resource stores available, taking into account whether the containing store is enabled and if its requiredCookie matches. Relative URLs are interpreted according to the current page location.
createStore(string name, [string requiredCookie])
Return Value ResourceStore
Parameters name - string identifying the store.
requiredCookie - optional.
The combination of name and requiredCookie (along with the domain) identify a unique store.
Expected cookie format is "name=value".
Exceptions Throws a JavaScript exception if an errors occurs.
Description Opens an existing ResourceStore or creates a new one if no such store exists.

If a requiredCookie is given, creates a ResourceStore that requires the cookie to be present in the client in order to serve the contents from the store.
openStore(string name, [string requiredCookie])
Return Value ResourceStore
null - if no such store exists
Parameters name - string identifying the store.
requiredCookie - optional.
The combination of name and requiredCookie (along with the domain) identify a unique store.
Expected cookie format is "name=value".
Exceptions Throws a JavaScript exception if an errors occurs.
Description Opens an existing ResourceStore or returns null if no such store exists. If the store was originally created with a requiredCookie, the same value must be provided in order to open this ResourceStore.
removeStore(string name, [string requiredCookie])
Return Value void
Parameters name - string identifying the store.
requiredCookie - optional.
The combination of name and requiredCookie (along with the domain) identify a unique store.
Expected cookie format is "name=value".
Exceptions Throws a JavaScript exception if an errors occurs.
Description Removes a ResourceStore and deletes all of its contents.
createManagedStore(string name, [string requiredCookie])
Return Value ManagedResourceStore
Parameters name - string identifying the store.
requiredCookie - optional.
The combination of name and requiredCookie (along with the domain) identify a unique store.
Expected cookie format is "name=value".
Exceptions Throws a JavaScript exception if an errors occurs.
Description Opens an existing ManagedResourceStore or creates a new one if no such store exists.
openManagedStore(string name, [string requiredCookie])
Return Value ManagedResourceStore
Parameters name - string identifying the store.
requiredCookie - optional.
The combination of name and requiredCookie (along with the domain) identify a unique store.
Expected cookie format is "name=value".
Exceptions Throws a JavaScript exception if an errors occurs.
Description Opens an existing ManagedResourceStore or returns null if no such store exists.
removeManagedStore(string name, [string requiredCookie])
Return Value void
Parameters name - string identifying the store.
[requiredCookie]
Exceptions Throws a JavaScript exception if an errors occurs.
Description Removes a ManagedResourceStore and all of its contained URLs from the local cache.


ManagedResourceStore class

The ManagedResourceStore class is designed to cache a set of inter-dependent resources. For example, it can cache the set of resources required to bootstrap an application. The contents of a ManagedResourceStore are determined by the URLs listed in a manifest file. When all resources listed in the manifest have been captured, the LocalServer makes the set eligible for use. Periodically, the LocalServer checks for an updated manifest file. If the manifest file has been updated, LocalServer automatically downloads the updated set of resources.

A ManagedResourceStore is a container of cached URLs. Each distinct ManagedResourceStore is uniquely identified by these attributes:

  • name - a string identifying the store.
    Currently the name must consist only of visible ASCII characters excluding the following:
    / \ : * ? " < > | ; ,
    Before finalization of the API we expect to remove this restriction.
  • requiredCookie - a cookie of the format "name=value" or null
  • origin - the scheme, domain, and port of the current page.

An application can have many ManagedResourceStores.

The ManagedResourceStores class requires a manifest file to define the URLs to store. The manifest file is described in detail, below.

Attributes

Attribute Type Description
name readonly attribute string The name of this managed resource store.
requiredCookie readonly attribute string The cookie requirements of the store.
For further details see Cookies and the LocalServer. If empty, resources within this store are always served locally, provided the store is enabled.
enabled readwrite attribute boolean Enables local serving of URLs from this store when enabled=true. Disables local serving otherwise.
manifestUrl readwrite attribute string The location of the manifest file.
lastUpdateCheckTime readonly attribute int Time in second when the last update check occurred.
updateStatus readonly attribute int Can be one of four values:
0 Update OK. An update task is not running. The last update task to run succeeded.
1 Update checking. Gears is checking for a new manifest file.
2 Update downloading. Gears is found a new manifest and is downloading the new resources.
3 Update failed. An update task is not running. The last update task to run failed, and the error message is in the lastErrorMessage property.
lastErrorMessage readonly attribute string When updateStatus is 3 (update failed), this property contains details about the error.
currentVersion readonly attribute string The version of the set of resources that is currently being served locally, or empty string if no version is currently in use. This value reflects the version attribute from the manifest file only after all resources listed in the manifest file have been cached locally.

Methods

void checkForUpdate()
Return Value void
Parameters  
Exceptions  
Description

Explicitly initiates an update task that runs asynchronously in the background, and returns immediately.

An update task first issues a conditional GET of the manifest file from manifestUrl. If a response body is returned, the JSON data is parsed and the 'version' attribute is compared with the currentVersion property of the store. If they are different, the update task proceeds to GET each resource listed in the new manifest file. If the previous version contained a resource listed in the new version, the update task will issue an IfModifiedSince conditional request. While an update is in progress, resources from the previous version (if any) will continue to be served locally. After all resources have been downloaded, the currentVersion property will be updated to indicate that the new set of a resources are now being served locally and the previous version has been removed.

An additional HTTP header is added when Gears is capturing URLs
X-Gears-Google: 1

If an update task is interrupted in the middle, processing will resume where it left off the next time an update task for this store is initiated.

Note that the manifest file's version string is compared for equality against the current known version string, and if a different version is found, downloads it. No other types of comparisons are performed on the version string.

Update tasks are initiated automatically by Gears when resources stored in the ManagedResourceStore are requested and served.

 

 


ResourceStore class

A ResourceStore is a container of cached URLs. Each distinct ResourceStores is uniquely identified by three attributes:

  • name - a string name identifying the ResourceStore
    Currently the name must consist only of visible ASCII characters excluding the following:
    / \ : * ? " < > | ; ,
    Before finalization of the API we expect to remove this restriction.
  • requiredCookie - a cookie of the format "name=value" or null
  • domain - the domain, protocol and port of the current page.

There can be many ResourceStores in the system.

A ResourceStore is populated with URLs explicitly through the use of the JavaScript API that this class provides.

Attributes

Attribute Type Description
name readonly attribute string The name of the store that you provided upon creating this object.
requiredCookie readonly attribute string The cookie requirements of the store. For further details see Cookies and the LocalServer.
If requiredCookie is empty, then resources within this store are always served locally, provided the store is enabled.
enabled readwrite attribute boolean Enables local serving of URLs from this store when enabled=true. Disables local serving otherwise.

 

Methods

capture(urlOrUrlArray, callback)
Return Value int
Parameters urlOrUrlArray

callback(string url, boolean success, int captureId)
Exceptions Throws an exception if any of the URLs is not from the same origin as the current page.
Description

Initiates a capture task that runs asynchronously in the background, and returns immediately. The return value is a captureId which can be passed to abortCapture to cancel the task.

Relative URLs are interpreted according to the current page's location. Upon completion of each URL the callback function is invoked.

An additional HTTP header is added when Gears is capturing URLs
X-Gears-Google: 1

abortCapture(int captureId)
Return Value void
Parameters captureId
Exceptions  
Description Aborts a capture task.
remove(string url)
Return Value void
Parameters url
Exceptions Throws an exception if URL is not from the same origin as the current page.
Description Removes a cached URL from the store.
rename(string srcUrl, string destUrl)
Return Value void
Parameters srcUrl

destUrl
Exceptions Throws an exception if the source or destination URL is not from the same origin as the current page.
Description Renames a URL that is cached in the resource store.
copy(string srcUrl, string destUrl)
Return Value void
Parameters srcUrl

destUrl
Exceptions Throws an exception if the source or destination URL is not from the same origin as the current page.
Description Copies a cached URL.
isCaptured(string url)
Return Value boolean
Parameters url
Exceptions Throws an exception if the URL is not from the same origin as the current page.
Description Returns true if the URL is cached in the store.
captureFile(HtmlElement fileInputElement, string url)
Return Value void
Parameters fileInputElement

url
Exceptions Throws an exception if the URL is not from the same origin as the current page or if the file cannot be read.
Description Captures the contents of the file indicated by the fileInputElement into the store and associates that content with the given URL. The fileInputElement argument must be a reference to an <input type=file> HTML element.
getCapturedFileName(string url)
Return Value string
Parameters url
Exceptions Throws an exception if the url is not from the same origin as the current page.
Description Returns the leaf file name associated with url that was previously captured by calling captureFile. Note that if url was captured by a method other than calling captureFile then an empty string will be returned and no exception will be thrown.
getHeader(string url, string name)
Return Value string
Parameters url

name name of the header you want to retrieve, e.g. 'Content-Length'.
Exceptions Throws an exception if the url is not from the same origin as the current page.
Description Returns a specific HTTP header associated with the captured URL.
getAllHeaders(string url)
Return Value string
Parameters url
Exceptions Throws an exception if the url is not from the same origin as the current page.
Description Returns all HTTP headers associated with the captured url.
createFileSubmitter()
Return Value FileSubmitter
Description Returns a FileSubmitter object, which is used to submit URLs that are contained in this store in HTML form submissions.

FileSubmitter class

The FileSubmitter object facilitates the submission of local files, that were previously captured using ResourceStore.captureFile, in multipart/form-data encoded form submissions.

To create a FileSubmitter, call ResourceStore.createFileSubmitter(). The returned object allows only URLs contained in the originating resource store to be submitted.

Methods

setFileInputElement(htmlElement, url)
Return Value void
Parameters htmlElement

url
Exceptions Throws an exception if the URL is not from the same origin as the current page.
Description

Prepares the htmlElement to submit the file indicated by url. The htmlElement must be contained in an html form. When the form is submitted the file will be included as part of the resulting POST. The url is the captured resource's key in the originating Store. Relative URLs are interpreted according to the current page's location. The name attribute of htmlElement determines the parameter name associated with the uploaded file.

Due to differences between Firefox and Internet Explorer, this method's behavior is browser specific.

  • Firefox: The htmlElement must be a reference to an <input type="file"> element.
  • Internet Explorer: The htmlElement must NOT be a reference to an <input> of any type.
<form method="POST" enctype="multipart/form-data" />
  <input id="fileinput" type="file" name="formFieldName" />
  <link id="iefileinput" name="formFieldName" />
</form>

<script>
  var fileSubmitter = store.createFileSubmitter();
  var htmlElement = isIE ? document.getElementById("iefileinput")
                         : document.getElementById("fileinput");
  fileSubmitter.setFileInputElement(htmlElement, urlOfStoredResource);
</script>

 

Manifest File

A manifest file lists all of the URLs to be captured by a ManagedResourceStore. It also contains the version for the manifest file format, the version of the contents of the manifest, and an optional redirection URL.

Using the ManagedResourceStore requires that you create a manifest file.

The manifest file and all the URLs listed in it must follow the "same-origin policy", which means that all the URLs must originate from the same URI scheme, host, and port. See Gears and Security for more information.

An application can have any number of manifest files and ManagedResourceStores. You specify which manifest file to use when you create an instance of ManagedResourceStore.

The manifest file is written in JavaScript Object Notation (JSON) format.

Sample manifest file

{
  // version of the manifest file format
  "betaManifestVersion": 1,

  // version of the set of resources described in this manifest file
  "version": "my_version_string",

  // optional
  // If the store specifies a requiredCookie, when a request would hit
  // an entry contained in the manifest except the requiredCookie is
  // not present, the local server responds with a redirect to this URL.
  "redirectUrl":  "login.html",

  // URLs to be cached (URLs are given relative to the manifest URL)
  "entries": [
      { "url": "main.html", "src": "main_offline.html" },
      { "url": ".", "redirect": "main.html" },
      { "url": "main.js" }
      { "url": "formHandler.html", "ignoreQuery": true },
    ]
}

Contents of a manifest file

Manifest File JSON object: A single object contains the attribute-value pairs described below.

Note: All URLs can be provided as relative to the manifest file, or as fully-qualifed URIs.

Attribute
Value
Notes
"betaManifestVersion" 1 Required. Represents the version of the manifest file format itself. The manifest file is recognized only if this attribute and value appear and are correct.
"version" string Required. Represents the version, which you determine, of the manifest file's contents. This version is usually your application's version.
  • Version string is any value determined by your application.
  • String is case sensitive.
  • Any change in the version string indicates to Gears that the manifest file has changed.
"redirectUrl" URL Optional. The redirect URL is returned from the localServer if a "requiredCookie" is not present for the URL requested.
"entries" An array of URL resources, in JavaScript object format. (See table below for details.) Lists the URLs of all the resources to be captured for this manifest file.

 

The "entries" attribute in the manifest file is an array of URL resources, in JavaScript object format. The resource objects' attribute-value pairs are described below.

Attribute
Value
Notes
"url" URL Required. A URL of a resource to be stored locally and served when "url" is requested locally.

All URLs must follow the same-origin security policy.
"src" URL Optional. If "src" is present, the given URL is fetched and served when "url" is requested locally.

The"src" and "redirect" are mutually exclusive.
"redirect" URL Optional. If "redirect" is present, the local server responds with a 302 redirect to the given URL when "url" is requested locally.

The"src" and "redirect" are mutually exclusive.
"ignoreQuery" boolean (default is false) Optional. If the value is true the query string in the request URL is ignored when matching against this entry's URL.

For example, a request for formHandler.html?name=value can match the entries for the full URL including the query, or just the formHandler.html portion of the URL.

Note: An entry with an exact URL match takes precedence over a match found by ignoring the query string.

 

Cookies and the LocalServer

Both the ResourceStore and ManagedResourceStore support an optional requiredCookie attribute. This value causes LocalServer to examine cookies when deciding which resource to serve for a request. The attribute is used as follows:

requiredCookie
Behavior
"foo=bar" Serves the resource from the store if cookie foo is present in the request, and has the value bar.
"foo=;NONE;" Serves the resource from the store if cookie foo is not present in the request.

 

Location of cached files

The LocalServer stores files that your application captures in a location determined by the browser and platform.

Windows Vista - Internet Explorer

Location: {FOLDERID_LocalAppDataLow}\Google\Google Gears for Internet Explorer
Example: C:\Users\Bob\AppData\LocalLow\Google\Google Gears for Internet Explorer

Windows Vista - Firefox - Files are stored in the user local profile directory.

Location: C:\Users\<username>\AppData\Local\Mozilla\Firefox\Profiles\{profile}.default\Google Gears for Firefox
Example: C:\Users\Bob\AppData\Local\Mozilla\Firefox\Profiles\uelib44s.default\Google Gears for Firefox

Windows XP - Internet Explorer - Files are stored in the user local profile directory.

Location: C:\Documents and Settings\<username>\Local Settings\Application Data\Google\Google Gears for Internet Explorer
Example: C:\Documents and Settings\Bob\Local Settings\Application Data\Google\Google Gears for Internet Explorer

Windows XP - Firefox - Files are stored in the user local profile directory.

Location: C:\Documents and Settings\<username>\Local Settings\Application Data\Mozilla\Firefox\Profiles\{profile}\Google Gears for Firefox
Example: C:\Documents and Settings\Bob\Local Settings\Application Data\Mozilla\Firefox\Profiles\uelib44s.default\Google Gears for Firefox

Mac OS/X - Firefox - Files are stored in the user local profile directory.

Location: Users/<username>/Library/Caches/Firefox/Profiles/{profile}.default/Google Gears for Firefox
Example: Users/Bob/Library/Caches/Firefox/Profiles/08ywpi3q.default/Google Gears for Firefox

Linux - Firefox - Files are stored in the user home directory.

Location: ~bob/.mozilla/firefox/<firefox's profile id>/Google Gears for Firefox
Example: ~bob/.mozilla/firefox/08ywpi3q.default/Google Gears for Firefox