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.

Applications manage the cache using two classes:

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

Serving and updating cached resources

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

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.

A key difference between the two types of stores is how resources are updated. The contents of a ManagedResourceStore are automatically updated periodically by Gears, even if the web developer never calls checkForUpdate(). For more information, see ManagedResourceStore Updates. The ResourceStore's contents are never automatically updated, and are only updated when the developer explicitly calls capture().

Permission

This API requires user permission. If you would like to customize the default dialog, you can explicitly call google.gears.factory.getPermission() - see how.

 

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
   event void oncomplete(Object details)
   event void onerror(Error error)
   event void onprogress(Object details)
   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          captureBlob(Blob blob, string url, string optContentType)
   void          captureFile(fileInputElement, url)
   string        getCapturedFileName(url)
   string        getHeader(string url, string name)
   string        getAllHeaders(string url)
   Blob          getAsBlob(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:

An application can have many ManagedResourceStores.

The ManagedResourceStores class requires a manifest file to define the URLs to store, and the rules to determine which resource to return for a requested URL. 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 is not running. The last update 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 is not running. The last update 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.

Events

event void oncomplete(Object details)
Parameters details An object containing information about the update. Contains one property:
    • String newVersion - The new version of the ManagedResourceStore if the version changed. Otherwise, an empty string.
Description

This event is fired when a ManagedResourceStore completes an update. Note that updates can be either started explicitly, by calling checkForUpdate(), or implicitly, when resources are served from the store.

An update may or may not result in a new version of the store. If a new version results, the newVersion property of the details object will contain the store's new version string.

event void onerror(Error error)
Parameters error Contains details about the error that occured. Contains one property:
    • String message - The error message.
Description This event is fired when a ManagedResourceStore update fails. Note that update failure may occur normally when an application is running offline, or if the server is down.
event void onprogress(Object details)
Parameters details Contains information about the progress of a ManagedResourceStore update. Contains the following properties:
    • Number filesComplete - The number of files that have been captured so far in the current update.
    • Number filesTotal - The total number of files that need to be captured in the current update.
Description This event is fired periodically during a ManagedResourceStore update. The filesTotal property contains the total number of files found in the manifest that need to be fetched. The filesComplete property contains the number of files that have been fetched so far. You can use this information to show progress information to the user.

Methods

void checkForUpdate()
Return Value void
Parameters  
Exceptions  
Description

Explicitly initiates an update that runs asynchronously in the background, and returns immediately. For more details, see Managed Resource Store Updates.



ManagedResourceStore Updates

ManagedResourceStores can be updated both manually and automatically.

An update can be started manually by calling checkForUpdate(). Many web applications will only ever need to manually update a ManagedResourceStore the very first time, to capture the intial version of an application. An automatic update is started each time Gears intercepts and serves a request from a ManagedResourceStore. Both types of updates are limited so that they do not occur more frequently than once every 10 seconds.

An update 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 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 will issue an If-Modified-Since conditional request.

Note that Gears compares manifest version strings for equality. Any change in a version string, even numerical changes like "2" to "1", will trigger an update.

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.

Manifest Validation

After all the resources in a manifest have been successfully updated, Gears sends a final conditional GET request for the manifest to ensure that its version has not changed since the update started.

In this request, Gears sends the special HTTP header X-Gears-Reason: validate-manifest. The server can respond with the manifest contents, or with 304 Not Modified.

If the manifest version changes in this second request, Gears retries the entire update once.

Retrying Resources

A server can indicate that Gears should retry the request for a particular resource by responding with 503 Service Unavailable and the HTTP header Retry-After: 0.

Gears will try requesting a particular resource up to three times. If the third attempt fails, Gears restarts the entire update from the beginning. Gears will try up to three updates.

The retry feature can be useful for applications that are load-balanced across a server farm where updates roll out slowly over the entire farm. If a server cannot serve a particular resource, it can indicate that Gears should try again.

Other Details

An additional HTTP header is added when Gears is capturing URLs:
X-Gears-Google: 1
Applications can use this header to return different resources to a Gears capture request than they would normally serve for the same URL.

If an update fails for any reason, such as a network error or server error, the next update first re-fetches the manifest to see if the version number has changed since the last run. If the version number is the same, the update resumes where the previous update left off. Otherwise, the previous update is discarded and the new update starts again at the first resource.

 


ResourceStore class

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

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 an update that runs asynchronously in the background, and returns immediately. The return value is a captureId which can be passed to abortCapture to cancel the update.

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.
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.
captureBlob(Blob blob, string url, string optContentType)
Return Value void
Parameters blob
url
optContentType
Exceptions Throws an exception if the URL is not from the same origin as the current page.
Description Captures the contents of the blob as the response body for the given URL. If optContentType is provided, the 'Content-Type' header is set to this value.
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.
DEPRECATED. This is currently only implemented in IE & Firefox.
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.
DEPRECATED. This is currently only implemented in IE & Firefox.
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.
getAsBlob(string url)
Return Value Blob
Parameters url
Exceptions Throws an exception if the URL is not from the same origin as the current page or if there is no entry for the URL.
Description Returns the body of the captured resource as a blob.
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

DEPRECATED. FileSubmitter is currently only implemented in IE & Firefox. Whenever possible, prefer the Blob support provided by desktop.openFiles() and the HttpRequest module.

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.
DEPRECATED. This is currently only implemented in IE & Firefox. Whenever possible, prefer the Blob support provided by desktop.openFiles() and the HttpRequest module.
<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, and the rules to determine which resource to return for a requested URL. 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 or 2 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.
  • "src" and "redirect" are mutually
exclusive options.
"redirect" URL Optional. If "redirect" is present, the local server responds with a 302 redirect to the given URL when "url" is requested locally.
  • "src" and "redirect" are mutually exclusive options.
"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.
  • "ignoreQuery" and "matchQuery" are mutually exlusive options.
  • Ex. 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.
  • An entry with an exact URL match takes precedence over a match found by ignoring the query string.
"matchQuery" object Optional. A set of conditions to apply to the query arguments of the requested URL. All of the conditions must be met to return the resource associated with this "entry".
  • "ignoreQuery" and "matchQuery" are mutually exlusive options.
  • Introduced in "betaManifestVersion": 2. To use this attribute, you must specify version 2.
  • An entry with an exact URL match takes precedence over a match found according to the matchQuery rules.

 

The "matchQuery" attribute of an "entry" defines a set of conditions to apply to the query arguments of the requested URL. The resource associated with the entry will only be returned if all of the conditions are met.

Attribute
Value
Notes
"hasAll" string Optional. The requested URL must have all of these arguments.
"hasSome" string Optional. The requested URL must have at least one of these arguments. The same 'name', with different values, can be present in the hasSome string more than once.
"hasNone" string Optional. The requested URL must have none of these arguments. The same 'name', with different values, can be present in the hasNone string more than once.

 

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 Vista - Chrome - Files are stored in the user local profile directory.

Location: C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\Plugin Data\Google Gears
Example: C:\Users\Bob\AppData\Local\Google\Chrome\User Data\Default\Plugin Data\Google Gears

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

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

Location: C:\Documents and Settings\<username>\Local Settings\Application Data\Google\Chrome\User Data\Default\Plugin Data\Google Gears
Example: C:\Documents and Settings\Bob\Local Settings\Application Data\Google\Chrome\User Data\Default\Plugin Data\Google Gears

Mac OS X - Safari - Files are stored in the user Application Support directory.

Location: ~/Library/Application Support/Google/Google Gears for Safari
Example: /Users/Bob/Library/Application Support/Google/Google Gears for Safari

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