use browser.alarms api

This commit is contained in:
Thomas Rupprecht 2022-12-25 16:45:34 +01:00
parent 6b69d7cd6a
commit de70d42b2b
3 changed files with 22 additions and 15 deletions

View File

@ -11,7 +11,7 @@ async function fetchJson(url) {
/**
* @param {number} days
* @returns {Promise<object>}
* @returns {Promise<Array<object>>}
*/
function fetchCalendar(days = 28) {
let url = `${Config.calenderUrl}?o=json`;
@ -66,25 +66,31 @@ async function fetchNewData() {
}
}
let intervalHandler = null;
function stopFetching() {
if (intervalHandler !== null) {
clearInterval(intervalHandler);
intervalHandler = null;
/**
* @param {Alarm} alarm
*/
function handleAlarm(alarm) {
if (alarm.name === 'fetchData') {
fetchNewData();
}
}
function startFetching() {
fetchNewData();
if (intervalHandler === null) {
intervalHandler = setInterval(() => {
fetchNewData();
}, Config.refreshTimeout);
}
browser.alarms.onAlarm.addListener(handleAlarm);
const now = new Date();
now.setMinutes(Math.ceil((now.getMinutes() + 1) / Config.refreshTimeout) * Config.refreshTimeout, 0, 0);
browser.alarms.create('fetchData', {
when: now.getTime(),
periodInMinutes: Config.refreshTimeout,
});
}
window.addEventListener('offline', () => {
stopFetching();
window.addEventListener('offline', async () => {
browser.alarms.onAlarm.removeListener(handleAlarm);
await browser.alarms.clear('fetchData');
});
window.addEventListener('online', () => {
startFetching();

View File

@ -1,5 +1,5 @@
export default {
refreshTimeout: 1000 * 60 * 5, // 5min,
refreshTimeout: 5,
spaceApiUrl: 'https://www.usrspace.at/spaceapi.json',
calenderUrl: 'https://www.usrspace.at/calendar.php',
openColor: '#33cc33',

View File

@ -20,6 +20,7 @@
"default_locale": "de",
"permissions": [
"https://www.usrspace.at/*",
"alarms",
"notifications",
"storage",
"webRequest"