Search code examples
javascriptgoogle-chrome-extension

Run a function when closing google popup extension


I have an alarm function in my extension, but when I close it I want it to clear the alarms, how can I do that?

Basically when I start my alarm, even when the extension is closed it will try to trigger the alarm function.

background.js:

chrome.action.onClicked.addListener((tab) => {
    chrome.windows.create({
        url: chrome.runtime.getURL("/popups/popup.html"),
        type: "popup",
        width: 350,
        height: 480
    },(win)=>{
        chrome.storage.local.set({'winId': win.id});
    })
});


chrome.alarms.onAlarm.addListener(async function(alarm) {
    let teste
    await chrome.storage.local.get(['winId']).then((result) => {
        teste = result.winId;
    });
    chrome.windows.update(teste, {focused: true});
});

I thought it would have some google.onclosed function, but I didn't find something like that.


Solution

    1. use chrome.storage.session not chrome.storage.local to store winId
    2. use chrome.windows.onRemoved event in the background script
    chrome.windows.onRemoved.addListener(async id => {
      const {winId} = await chrome.storage.session.get('winId');
      if (winId === id) {
        chrome.alarms.clearAll();
      }
    }, ['popup']); // filtering by popups because our window was created with type: 'popup'