mirror of
https://github.com/GoogleChrome/chrome-extensions-samples.git
synced 2026-03-27 13:29:34 +07:00
* [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
38 lines
1.0 KiB
JavaScript
38 lines
1.0 KiB
JavaScript
console.log('sw-tips.js');
|
|
|
|
// Fetch tip & save in storage
|
|
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);
|
|
return chrome.storage.local.set({ tip: tips[randomIndex] });
|
|
};
|
|
|
|
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);
|
|
|
|
// Send tip to content script via messaging
|
|
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
|
if (message.greeting === 'tip') {
|
|
chrome.storage.local.get('tip').then(sendResponse);
|
|
return true;
|
|
}
|
|
});
|