An API to detect if a Chrome Extension has updated

As you might have been able to tell from my previous posts, I am a bit of a nut when it comes to the Management API in the Chrome Extension framework.

I got asked a question recently about detecting if a Chrome Extension has been updated. The good news is that there is an API for that. The bad news is that I told a little fib: there isn’t actually a specific API for detecting if an Extension/App had been updated.

Lets get back on to the Good News, you can detect if an Extension/App has been updated by listening to the onInstalled event triggered by Chrome. Every time an extension is installed (or updated) this event gets fired.

The important thing to remember is that it doesn’t tell you directly if the installation was an update, so the thing that you need to do is first get a list of all the extensions installed by the user and then track the version number in onInstalled.

Here is a neat little sample of it in action:

/*
    Track all the version numbers (background.html) 
    in your background page
*/
var extensions = {};
var getAllCallback = function(exts) {
  for(var i in exts) {
    var ext = exts[i];
    extensions[ext.id] = ext; // store a reference to the app
  }
};

chrome.management.getAll(getAllCallback);

Now that we have a list of the apps, we can listen for installatons. In the handler, we are only going notify they user if the extension/app is not new and the version has changed. An extension is not new if we already know about it.

var onInstall = function(ext) {
  var id = ext.id;

  if(extensions[id] && extensions[id].version != ext.version) {
    chrome.browserAction.setBadgeText({"text" :"New" }); // tell the user  
    extensions[id] = ext; // track the extension
  }
};

Cool.