Unpossible
Unpossible

Reputation: 10697

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.

Upvotes: 3

Views: 5683

Answers (2)

ofix
ofix

Reputation: 1

I have written a chrome extension in manifest v3, here is my experimental code snippet, and it can detect the popup window properly.

// popup.js

const isElementVisible = (ele, partiallyVisible = false) => {
    const { top, left, bottom, right } = ele.getBoundingClientRect();
    const { innerHeight, innerWidth } = window;
    return partiallyVisible ? ((top > 0 && top < innerHeight) ||
         (bottom > 0 && bottom < innerHeight)) &&
         ((left > 0 && left < innerWidth) || 
         (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && 
          bottom <= innerHeight && right <= innerWidth;
};
let opened = false;
setInterval(function () {
    let ele = document.getElementById("app");
    if (isElementVisible(ele) && !opened) {
         chrome.runtime.sendMessage({ type: "popup_window_opened" });
         opened = true;
    }
 }, 1000);

// service_worker.js

 chrome.runtime.onMessage.addListener(function (message, sender,
      sendResponse) {
          if (message.type == "popup_window_opened") {
             console.log("popup window opened");
          }
 });

when I watch the service worker's console output, I found that every time when the popup window open, the interval timer in popup window would work and send a message to service worker, otherwise, the interval timer in popup window would stop and service worker can't receive any message.

Upvotes: 0

Xan
Xan

Reputation: 77523

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.

Upvotes: 2

Related Questions