I've seen the future of the web. It's in the background

* I will caveat this whole post with the a hefty disclaimer that this only works on the Dev Channel of Chrome and could change significantly over time.

Chrome introduced the notion of background pages to packaged apps and extensions. Background pages allow the app or extension to run without a UI surface – this is pretty cool because it allows for some really great use-cases that you don’t get with plain web applications; for example you can poll Twitter for updates that mention you and receive an alert via a Desktop Notification about the update.

Web-apps hosted on the open web have not had this ability, until now.

Chrome has recently brought this idea to the web with some added powers. Mainly:

  • Your web app can still run even when your app is closed,
  • Your web app can still run when the browser is closed,
  • Your web app can run after system start-up.

This is very powerful.

Actually let me re-phrase that. This is amazingly, unbelievably, stonkingly powerful. [definition: stonking]

So, how do you use them?

The good thing is it is really simple – a matter of two steps.

Step 1, this is currently only available to apps – not web sites. Apps in Chrome are defined using a manifest file. You as the developer must include a permission “background” to enable this feature. More on the permissions model can be found on code.google.com.

{
  "name" : "test",
  "version" : "0.0.0.1",
  "permissions" : ["background"],
  "app" : {
    "launch" : {
      "urls" : ["http://appmator.appspot.com/"],
      "web_url" : "http://appmator.appspot.com/"
    }
  }
}

Step 2, a little bit of Javascript magic…. actually, it is not magic, it is a simple call to window.open().

win = window.open("background.html#", "background", "background");

The detail is in the 3rd parameter which is reserved for specs. When Chrome is running with the “background” permission it will launch this page with no visible surface and track it in perpetuity.

By using window.open, it means that users and developers can toggle the state of the background running task by simply calling window.close, which will cause it to stop running. This also means that requesting window.open without a url, but with the background name will return a reference to the running window that can then be closed.

You can only open a url that is specified in the domain of the “urls” extents in the manifest – so for example you couldn’t open a background page to google.com if you didn’t verify you own that domain.

Now your app can run in the background. It will start up when the user logs into their machine, it will still be running when the user closes the visible browser (if you completely kill

POP QUIZ: How can my background page talk to my app pages?

ANSWER: SharedWorkers my hairy friend. Don’t use references to windows, that is so 2005.

In other exciting news, Appmator has been modified to support the “background” permission.