The original code I tried was this:
chrome.alarms.create("check-tabs", { periodInMinutes: .01, when: Date.now() + 500 });
chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name == "check-tabs") {
console.log("check-tabs");
chrome.tabs.query({ active: false, lastFocusedWindow: false }, function (tabs) {
for (i = 0; i < tabs.length; i++) {
if (chrome.alarms.get(tabs[i].url) == undefined) {
chrome.alarms.create(tabs[i].url, { when: Date.now() + 10 * 1000 })
}
}
});
} else {
console.log("not check-tabs, got alarm");
}
});
But the else statement would just ignore that it was the wrong alarm and display "not check-tabs". The same thing happened when i changed else to:
else if (alarm.name != "check-tabs")
The result was the same. The problem gets fixed when I change the code to:
chrome.alarms.create("check-tabs", { periodInMinutes: .01, when: Date.now() + 500 });
chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name == "check-tabs") {
console.log("check-tabs");
chrome.tabs.query({ active: false, lastFocusedWindow: false }, function (tabs) {
for (i = 0; i < tabs.length; i++) {
if (chrome.alarms.get(tabs[i].url) == undefined) {
chrome.alarms.create(tabs[i].url, { when: Date.now() + 10 * 1000 })
}
}
});
} else if (alarm.name == "random-alarm-name") {
console.log("not check-tabs, got alarm");
}
});
But in my code there are going to be multiple alarm names that are created when the code is running, so the names aren't concrete.
Note: I know it is not because of the alarm created by the first if statement, I tested it without creating that alarm and the result was the same.
Does anyone know how to fix this?
Likely your listener code gets called multiple times. Add an unconditional condole.log('called ' + alarm.name)
, and see how many of those get printed.