javascriptgoogle-chromegoogle-chrome-extensionalarms

Can you target an event listener to a specific Chrome Alarm?


I'm trying to create a Chrome Extension that uses two different alarms, using the Chrome Alarms API. I want to create two specific listeners, each handled by a different alarm:

chrome.alarms.onAlarm.addListener(function(timer) {
  reminder.displayMessage();
});

chrome.alarms.onAlarm.addListener(function(walk) {
  reminder.displayWalkMessage();
});


chrome.alarms.create('timer', {
  delayInMinutes: 5,
  periodInMinutes: parseInt(time)
});


chrome.alarms.create('walk', {
  delayInMinutes: 30,
  periodInMinutes: 60
});

The problem I'm having is that it seems when one alarm fires, both event handlers are triggered. Is there a way to specify which handler gets triggered by an alarm?


Solution

  • Replace the two event listeners with a single event listener:

    chrome.alarms.onAlarm.addListener(function(alarm) {
      if(alarm.name === "timer"){
          reminder.displayMessage();
      }
      else if(alarm.name === "walk"){
          reminder.displayWalkMessage();
      }
    });
    

    The argument to the callback function of onAlarm is an object of type alarm.