How to build a Chrome extension, Part 4: Background pages and scheduling requests

One of the most common uses for an extension is as a notifier. For example, the Google Gmail Checker, an official Google extension and the most popular one in the gallery, constantly checks your Gmail inbox for new unread mail.

This functionality is easy to add into your own extension. You need to add a background page, which is easily added by adding the background_page option to your manifest.json:

{
	"name": "My Extension",
	...
	"background_page": "background.html",
	...
}

Like almost every other component in a Chrome extension, background.html is a standard HTML file. However, it can also do things most web pages cannot, such as cross-origin requests if permissions are correctly added to the manifest. For example, if your extension is a Gmail checker, it would need permissions to http://www.google.com and https://www.google.com. To add these permissions, the manifest.json would be edited to:

{
	"name": "My Extension",
	...
	"background_page": "background.html",
	"permissions": ["http://www.google.com/", "https://www.google.com/"],
	...
}

A background page runs at all times when the extension is enabled. You cannot see it, but it can modify other aspects of the extension, like setting the browser action badge. For example, the following example would set the icon badge to the number of unread items in a hypothetical service:

function getUnreadItems(callback) {
	$.ajax(..., function(data) {
		process(data);
		callback(data);
	});
}

function updateBadge() {
	getUnreadItems(function(data) {
		chrome.browserAction.setBadgeText({text:data.unreadItems});
	});
}

So now you can make a request, but how can you schedule it so the data is retrieved and processed regularly? Luckily, JavaScript has a method called window.setTimeout to do just that:

var pollInterval = 1000 * 60; // 1 minute, in milliseconds

function startRequest() {
	updateBadge();
	window.setTimeout(startRequest, pollInterval);
}

That was easy! Now just slap a

onload='startRequest()'

on the background page’s body tag and that should do it!

But what if you want to stop the request? That can easily be done as well, by chaging the startRequest function a little and adding a stopRequest function:

var pollInterval = 1000 * 60; // 1 minute, in milliseconds
var timerId;

function startRequest() {
	updateBadge();
	timerId = window.setTimeout(startRequest, pollInterval);
}

function stopRequest() {
	window.clearTimeout(timerId);
}

And that’s about it on building background pages that can schedule requests. Now go! Make an awesome notifier! You can even make things like a timer with this (Facebook addiction control, anyone?). Just remember to leave a comment telling everyone of your awesomeness.