diff --git a/functional-samples/tutorial.quick-api-reference/sw-tips.js b/functional-samples/tutorial.quick-api-reference/sw-tips.js index 912d236d..d6400434 100644 --- a/functional-samples/tutorial.quick-api-reference/sw-tips.js +++ b/functional-samples/tutorial.quick-api-reference/sw-tips.js @@ -5,16 +5,25 @@ const updateTip = async () => { const response = await fetch('https://extension-tips.glitch.me/tips.json'); const tips = await response.json(); const randomIndex = Math.floor(Math.random() * tips.length); - await chrome.storage.local.set({ tip: tips[randomIndex] }); + return chrome.storage.local.set({ tip: tips[randomIndex] }); }; -// Create a daily alarm and retrieves the first tip when extension is installed. -chrome.runtime.onInstalled.addListener(({ reason }) => { - if (reason === 'install') { - chrome.alarms.create({ delayInMinutes: 1, periodInMinutes: 1440 }); +const ALARM_NAME = 'tip'; + +// Check if alarm exists to avoid resetting the timer. +// The alarm might be removed when the browser session restarts. +async function createAlarm() { + const alarm = await chrome.alarms.get(ALARM_NAME); + if (typeof alarm === 'undefined') { + chrome.alarms.create(ALARM_NAME, { + delayInMinutes: 1, + periodInMinutes: 1440 + }); updateTip(); } -}); +} + +createAlarm(); // Retrieve tip of the day chrome.alarms.onAlarm.addListener(updateTip);