The LocalServer module allows a web application to cache and serve its HTTP resources locally, without a network connection.
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.
The LocalServer intercepts HTTP/HTTPS requests and serves them from the cache when all of these conditions are met:
enabled attribute is set to true, and If the 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.
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().
This API requires user permission. If you would like to customize the default dialog, you can explicitly call google.gears.factory.getPermission() - see how.
<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" }
]
}
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 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)
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>
canServeLocally(string url)url - relative or absolute URL that is from the same origin as the current pagecreateStore(string name, [string requiredCookie])ResourceStorename - string identifying the store.requiredCookie - optional.openStore(string name, [string requiredCookie])ResourceStorenull - if no such store existsname - string identifying the store.requiredCookie - optional.removeStore(string name, [string requiredCookie])name - string identifying the store.requiredCookie - optional.createManagedStore(string name, [string requiredCookie])ManagedResourceStorename - string identifying the store.requiredCookie - optional.openManagedStore(string name, [string requiredCookie])ManagedResourceStorename - string identifying the store.requiredCookie - optional.removeManagedStore(string name, [string requiredCookie])name - string identifying the store.[requiredCookie]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.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.
enabled.enabled=true. Disables local serving otherwise.lastErrorMessage property.version attribute from the manifest file only after all resources listed in the manifest file have been cached locally.event void oncomplete(Object details)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.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)error Contains details about the error that occured. Contains one property:String message - The error message.event void onprogress(Object details)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.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.void checkForUpdate()Explicitly initiates an update that runs asynchronously in the background, and returns immediately. For more details, see Managed Resource Store 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.
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.
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.
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.
A ResourceStore is a container of cached URLs. Each distinct ResourceStores is uniquely identified by three attributes:
name - a string name identifying the ResourceStorerequiredCookie - 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.
enabled.enabled=true. Disables local serving otherwise.
capture(urlOrUrlArray, callback)urlOrUrlArraycallback(string url, boolean success, int captureId)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)captureIdremove(string url)urlrename(string srcUrl, string destUrl)srcUrldestUrlcopy(string srcUrl, string destUrl)srcUrldestUrlisCaptured(string url)urlcaptureFile(HtmlElement fileInputElement, string url)fileInputElementurlfileInputElement 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)urlurl is not from the same origin as the current page.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)urlname name of the header you want to retrieve, e.g. 'Content-Length'.url is not from the same origin as the current page.getAllHeaders(string url)urlurl is not from the same origin as the current page.url.createFileSubmitter()FileSubmitterFileSubmitter object, which is used to submit URLs that are contained in this store in HTML form submissions.DEPRECATED. FileSubmitter is currently only implemented in IE & Firefox 2. 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.
setFileInputElement(htmlElement, url)voidhtmlElementurlPrepares 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.
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.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>
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 },
]
}
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.
"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.
"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.
"url" URL Required. A URL of a resource to be stored locally and served when "url" is requested locally."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."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."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.formHandler.html?name=value can match the entries for the full URL including the query, or just the formHandler.html portion of the URL.
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:
"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.
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
You are viewing a mobilized version of this site...
View original page here