Search code examples
javascriptgoogle-chrome-extension

Detecting when a Chrome Extension popup is opened


I am trying to wire some analytics into the onStartup event of my Chrome Extension per the docs. However, the event never seems to fire when the extension is opened via the icon in the browser.

Note that the onInstalled event in the below code fires as expected when the extension is installed, reloaded, etc.

chrome.runtime.onInstalled.addListener(function(details) {
  console.log('Extension installed: ' + details.reason);
});
chrome.runtime.onStartup.addListener(function() {
  console.log('Extension started');
});

Note I'm running Chrome v37 - the onStartup event has been available since v23.


Solution

  • You are trying to invoke code when a popup is opened. This is not the same as "starting" the extension - the chrome.runtime.onStartup event normally fires once per browser launch.

    chrome.browserAction.onClicked event will not fire when a popup page is set; instead, you need to execute some code in the popup page itself (and that code will be executed each time the popup is opened).

    You can simply send your analytics event from the popup page itself. Or, if you prefer sending it from the background page, you just need to message it.