Standalone Ajax with Gears, tutorial
Making Ajax work offline and using the browser as an application platform is quite simple. Install the Gears plugin and use the basic scripts included in this tutorial as a starting point.
This tutorial is simplified: our first application displays only the message "Hello World!," But it does it without an Internet connection when we type the URL of the demo page...
Then we go further with an offline gallery of images, and later see how to add buttons, menus, lists and any other widgets...
IMPORTANT: Gears is a portable solution that can be used right away, but Google decided to turn to HTML 5, for long-term development it is better to opt for the offline HTML 5 API.
Why Ajax offline?
When using standalone Ajax, it becomes possible to use the web page as a graphical interface for a locally running script. In fact, as we explain in the second demonstration, the system becomes a way to install applications and update them instantly, very simply.
It is important that the same app works responsibly, whether offline or online, hence the interest in combining these two technologies, Gears and Ajax.
Gears, review
To create an offline application, you need to use the Gears API, which is loaded with the plugin.
Its overall architecture uses the following components:
- LocalServer, a local resource server that establishes synchronization between data on the server and the local copy.
- A working pool that controls the execution of JavaScript code.
- a desktop module for launching the application on the desktop.
- SQLite database for replicating SQL database content on the server.
- JavaScript library, including XMLHttpRequest and clock.
In addition, the geolocation module adapts the application for countries.
For a more general overview of the plugin, see Google Gears.
Using Gears
The user must download and install the plugin (with the exception of Chrome, where it is integrated) for the visited site in order to use Gears.
When the plugin is installed and the user visits a site that supports this option, they are asked if they want the site to use Gears and thus enable local data saving.
Then the visitor can continue to view the content of this site, as it is at the time of login, in your browser and without access to the Internet. For example, view the contents of the mailbox as they were when you logged in.
If you change something in your account, the changes will be propagated to the site the next time you sign in .
Services like Docs from Google can provide access to This option is enabled automatically.
Gears Page Structure
The gears page should contain some scenarios and possibly have an area to display the status of the gears.
Including scenarios
<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript" src="gears_offline.js"></script>
<script type="text/javascript" src="ajax-gears.js"></script>
gears_init.js initializes Gears, but does not prepare for offline mode.
gears_offline.js initializes offline mode or returns to online mode, offering the user a choice; it is associated with buttons.
ajax-gears.js is our script for combining Ajax and Gears.
Page text
<body> <div id="textOut"></div> <button onClick="createStore()"> Go offline </button>
<button onClick="removeStore()"> Go back online </button> </body>
The page contains two buttons. They call the createStore () and removeStore () functions to go offline or back online. The textOut field displays status messages for the gears.
Option: Since we added the script, we chose to initialize Gears by calling the init () function from it. Otherwise, we would have to add an attribute to the <body> tag:
<body onload="init">
Automatic offline mode
You can launch the createStore () function immediately after initializing Gears and remove two buttons, so the application will always work offline. But if you want to be able to update scripts and other resources, buttons are necessary.
The Gears Code
This filegears_init.js is provided by Google, and the programmer does not need to worry about it.
The gears_offline.js file is a modified version of the Google go_offline.js file.
Functions and Variables in gears_offline.js
in it()
A Gears-managed local store is created.
createStore ()
Documents are stored locally. This depends on the manifest file that lists the affected files and scripts.
removeStore ()
It redirects the user to a live site and deletes the local space.
In addition to these functions, the file contains STORE_NAME and MANIFEST_FILENAME variables. The second contains the manifest file name, manifest.json by default.
manifest.json file
In the example, it contains the following lines:
{
"betaManifestVersion": 1,
"version": "1.0",
"entries": [
{ "url": "ajax-offline-demo.html"},
{ "url": "gears_offline.js"},
{ "url": "gears_init.js"},
{ "url": "ajax-gears.js"}
]
}
URLs are the URLs of a web application, in this case a simple demo page and scripts. You must specify any other files required by the application.
Ajax Code
Gears installation uses Ajax code included in the Gears framework. Otherwise, we must return to the classic Ajax code using the browser-recognized XMLHttpRequest object.
To do this, we define a function that creates an instance based on an available object and a browser:
function gearsCreate() { var xhr = google.gears.factory.create('beta.httprequest'); if(!xhr) { try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (err1) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (err2) { try { xhr = new XMLHttpRequest(); } catch (err3) { xhr = false; } } } } return xhr; }
In terms of object attributes and methods, the Gears, XMLHttpRequest, and ActiveX attributes are the same, and so the rest of the code is common to all three cases.
GET Usage Example
Download a text file named "xhr-demo.txt."
var xhr = createXHR(); xhr.open('GET', "xhr-demo.txt"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { alert(xhr.responseText); } }; xhr.send();
The createXHR call instantiates the Gears/XMLHttpRequest/ActiveX object assigned to the xhr variable.
The contents of the file are loaded into xhr.responseText and displayed in the warning window.
Minimal demonstration using GET method
To begin with, we simply define an Ajax application that simply loads the contents of the file using the GET method and displays the contents on the page.
We use the createXHR () function and the gearsGet () function, which repeats the previous code, but which we give the name of the extracted file as parameters. load and the name of the function that processes the contents of this file after loading.
function gearsGet(xhr, fun, filename) { xhr.open('GET', filename); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { fun(xhr.responseText); } }; xhr.send(); }
function storing(result) { var storage = document.getElementById("storage"); storage.innerHTML = result; }
function demo() { init(); // starts gears var xhr = gearsCreate(); // creates an XHR object gearsGet(xhr, storing, 'xhr-demo.txt'); // loads a file on the server } window.onload=demo;
The demo () function initializes Gears, creates an instance, and calls gearsGet () with the name of the file to load and the name of the saving function to process the content.
The storing () function displays the contents of the file in the highlighted area of the ID storage page.
Offline Robot Gallery
This demo, which displays a photo gallery, is the beginning of an offline web application, as well as the beginning of a new way to install software on your desktop.
Here's how apps will work in the near future:
- We connect to the distributor's website.
- We bookmark the application page.
- Please switch to offline mode, which instructs Gears to copy all files and scripts of the application locally. At the same time, the gallery photographs and displays scripts.
- We can then access the gallery from You can update the gallery at any time by clicking on the bookmark link.
- To update your gallery, switch back online, and then go offline for a new sync that replaces and adds files.
In fact, this is tantamount to going to the distributor's website and downloading software, with the advantage of a simplified update.
The developer must place a list of all gallery images in the manifest file. We renamed the file gallery.json.
You also need to change the name assigned to the MANIFEST_FILENAME variable in the gears_offline.js file. But there is no need to modify the file; just reassign the variable in the script itself. application, gallery.js.
This application uses Ajax to load images into memory as the user views them, eliminating latency. The latency is minimal when the application is offline, but our application needs to work both offline and online.
The script calls the preloading () function for each image in the gallery. It loads the image asynchronously and starts when the page loads.
The enlarge () function displays the image in large format in a special <div> called bigview.
function enlarge(element) { var name = element.src; name = localFilename(name); name = name.slice(6); // remove the "thumb-" leaves name = "robots/" + name; // restore path var str = "<img src='" + name + "' >"; document.getElementById("bigview").innerHTML = str; }
The demo () function uses the gallery.js file
scenariofunction demo() { MANIFEST_FILENAME = "gallery.json"; // changing manifest file init(); // start gears preloading("robots/asimo.jpg"); preloading("robots/manoi.jpg"); preloading("robots/nao.jpg"); preloading("robots/robonova.jpg"); preloading("robots/repliee.jpg"); } window.onload=demo; // launched when the page is displayed
Demo and Downloads
Problems and limitations
In case of problems, clear the buffer. In Firefox, go to Tools -> Clear My Traces -> Check Cache. Clear other saved data if you do not want to delete it. Then confirm.
You can use the operating system control panel for Internet Explorer.
When the document is offline, it becomes impossible for the developer to update the resources associated with the application. They are uploaded to the server but cannot be uploaded. You must go offline to make the modified versions available.
Both demos have been tested and are working, but if you have multiple apps offline at the same time, they may not work.
The Ajax POST method can work, but the server PHP script for processing the received data is not synchronized by Gears; the app would only work online, as stated in the Gears FAQ.Tools and links
- Thumbnail Maker is a resizing script used for robot sketches.
- Humanoid robots. Read more about the robots featured in the gallery.