winzik/skeleton-chrome/background.js

48 lines
2.2 KiB
JavaScript

// The background service worker (Manifest V3): it starts when an event needs it and stops when idle, so it keeps
// nothing in variables between events: state goes to chrome.storage. Every listener is registered at the top level,
// synchronously, or Chrome does not wake the worker for it.
import { getSettings, saveSettings } from './lib/settings.js';
const MENU_ID = 'highlight-selection';
const ALARM = 'background-check';
// installed or updated: the context menu (menus survive restarts, create them once here) and a periodic alarm
chrome.runtime.onInstalled.addListener(async () => {
chrome.contextMenus.create({ id: MENU_ID, title: chrome.i18n.getMessage('menuHighlight'), contexts: ['selection'] });
await chrome.alarms.create(ALARM, { periodInMinutes: 60 });
await chrome.storage.local.set({ lastCheck: Date.now() });
});
// the context menu: the selected text becomes the word to highlight, the tab is highlighted again
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId !== MENU_ID || !info.selectionText) return;
await saveSettings({ term: info.selectionText });
if (tab?.id !== undefined) chrome.tabs.sendMessage(tab.id, { type: 'highlight' }).catch(() => {});
});
// the alarm: an example of periodic work (fetch something, clean old data...); here it only notes the time
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === ALARM) await chrome.storage.local.set({ lastCheck: Date.now() });
});
// messages from the content script and the popup. Return true to answer later (sendResponse after an await).
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
switch (message?.type) {
case 'getSettings':
getSettings().then(sendResponse);
return true;
case 'count': {
// the content script counted the matches of its tab: the number on the toolbar button
const tabId = sender.tab?.id;
if (tabId !== undefined) {
const text = message.count > 0 ? String(Math.min(message.count, 999)) : '';
chrome.action.setBadgeText({ tabId, text });
chrome.action.setBadgeBackgroundColor({ tabId, color: '#5b4bdb' });
}
sendResponse({ ok: true });
return false;
}
default:
return false;
}
});