Skip to content

Commit 4aa6bdb

Browse files
authored
[SW-tutorial] Refactor alarms API logic (sw-tips.js) (GoogleChrome#865)
* [SW-tutorial] Refactor alarms API logic After doing some experiments (like closing all my browser windows which I never, EVER do...) I realized the tips logic was not working as expected, because [alarms do not persist across browser sessions[(https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms#:~:text=Alarms%20do%20not%20persist%20across%20browser%20sessions.) * Return storage set * Tech review
1 parent 0cd6920 commit 4aa6bdb

File tree

1 file changed

+15
-6
lines changed
  • functional-samples/tutorial.quick-api-reference

1 file changed

+15
-6
lines changed

functional-samples/tutorial.quick-api-reference/sw-tips.js

+15-6
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,25 @@ const updateTip = async () => {
55
const response = await fetch('https://extension-tips.glitch.me/tips.json');
66
const tips = await response.json();
77
const randomIndex = Math.floor(Math.random() * tips.length);
8-
await chrome.storage.local.set({ tip: tips[randomIndex] });
8+
return chrome.storage.local.set({ tip: tips[randomIndex] });
99
};
1010

11-
// Create a daily alarm and retrieves the first tip when extension is installed.
12-
chrome.runtime.onInstalled.addListener(({ reason }) => {
13-
if (reason === 'install') {
14-
chrome.alarms.create({ delayInMinutes: 1, periodInMinutes: 1440 });
11+
const ALARM_NAME = 'tip';
12+
13+
// Check if alarm exists to avoid resetting the timer.
14+
// The alarm might be removed when the browser session restarts.
15+
async function createAlarm() {
16+
const alarm = await chrome.alarms.get(ALARM_NAME);
17+
if (typeof alarm === 'undefined') {
18+
chrome.alarms.create(ALARM_NAME, {
19+
delayInMinutes: 1,
20+
periodInMinutes: 1440
21+
});
1522
updateTip();
1623
}
17-
});
24+
}
25+
26+
createAlarm();
1827

1928
// Retrieve tip of the day
2029
chrome.alarms.onAlarm.addListener(updateTip);

0 commit comments

Comments
 (0)