-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
62 lines (53 loc) · 1.75 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const ALARM_NAME = 'fetch-police-logs';
const UPDATE_INTERVAL = 5; // minutes
const API_URL = 'https://api.politiet.no/politiloggen/v1/rss?districts=Vest';
async function fetchAndStoreLogs() {
try {
const response = await fetch(API_URL, {
headers: {
'User-Agent': 'Police-Logs-Extension/1.0',
'Accept': 'application/rss+xml'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
const parser = new DOMParser();
const xml = parser.parseFromString(text, 'text/xml');
const items = Array.from(xml.querySelectorAll('item')).slice(0, 5);
const logs = items.map(item => ({
title: item.querySelector('title')?.textContent || '',
description: item.querySelector('description')?.textContent || '',
pubDate: item.querySelector('pubDate')?.textContent || '',
link: item.querySelector('link')?.textContent || '',
timestamp: new Date().getTime()
}));
await chrome.storage.local.set({
logs,
lastUpdated: new Date().toISOString(),
error: null
});
} catch (error) {
console.error('Error fetching logs:', error);
await chrome.storage.local.set({
error: 'Unable to fetch police logs. Please try again later.',
lastUpdated: new Date().toISOString()
});
}
}
// Initialize when extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
// Set up alarm for periodic updates
chrome.alarms.create(ALARM_NAME, {
periodInMinutes: UPDATE_INTERVAL
});
// Initial fetch
fetchAndStoreLogs();
});
// Fetch logs when alarm triggers
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === ALARM_NAME) {
fetchAndStoreLogs();
}
});