Detect Chrome extension first run / update

How can an extension find out that it is being run for the first time or has just been updated, so that the extension can perform some specific actions? (e.g. open a help page or update settings)


Solution 1:

In newer versions of Chrome (since Chrome 22), you can use the chrome.runtime.onInstalled event, which is much cleaner.

Example:

// Check whether new version is installed
chrome.runtime.onInstalled.addListener(function(details){
    if(details.reason == "install"){
        console.log("This is a first install!");
    }else if(details.reason == "update"){
        var thisVersion = chrome.runtime.getManifest().version;
        console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
    }
});

Solution 2:

Updated answer to reflect v3 of manifest:

Chromium now has a chrome.runtime set of APIs, which allow you to fetch the version of the extension.

To get the current version:

chrome.runtime.getManifest().version

To listen when the extension has been first installed, when the extension is updated to a new version, and when Chromium is updated to a new version, you can use the onInstalled event.

chrome.runtime.onInstalled.addListener((details) => {
   const currentVersion = chrome.runtime.getManifest().version
   const previousVersion = details.previousVersion
   const reason = details.reason
   
   console.log('Previous Version: ${previousVersion }')
   console.log('Current Version: ${currentVersion }')

   switch (reason) {
      case 'install':
         console.log('New User installed the extension.')
         break;
      case 'update':
         console.log('User has updated their extension.')
         break;
      case 'chrome_update':
      case 'shared_module_update':
      default:
         console.log('Other install events within the browser')
         break;
   }

})

Thats all!


Old answer, prior to 2011

If you want to check if the extension has been installed or updated, you can do something like this:

function onInstall() {
    console.log("Extension Installed");
  }

  function onUpdate() {
    console.log("Extension Updated");
  }

  function getVersion() {
    var details = chrome.app.getDetails();
    return details.version;
  }

  // Check if the version has changed.
  var currVersion = getVersion();
  var prevVersion = localStorage['version']
  if (currVersion != prevVersion) {
    // Check if we just installed this extension.
    if (typeof prevVersion == 'undefined') {
      onInstall();
    } else {
      onUpdate();
    }
    localStorage['version'] = currVersion;
  }