winzik/skeleton-chrome/popup/popup.js

48 lines
1.8 KiB
JavaScript

// The popup (the toolbar button's page). It lives only while it is open: save at once, keep nothing here.
import { getSettings, saveSettings } from '../lib/settings.js';
import { t, translatePage } from '../lib/i18n.js';
translatePage();
const term = document.getElementById('term');
const countLine = document.getElementById('count');
/** The tab the popup acts on: the active one (activeTab gives access to it on click), or ?tab=<id> (tests, chrome:run). */
async function targetTab() {
const id = Number(new URLSearchParams(location.search).get('tab'));
if (id) return chrome.tabs.get(id);
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab;
}
function showCount(response) {
countLine.textContent = response ? t('matchesOnPage', [String(response.count)]) : t('notAvailable');
}
async function ask(type) {
const tab = await targetTab();
if (tab?.id === undefined) return null;
// no content script in this tab (a page outside "matches", chrome:// pages...): sendMessage rejects
return chrome.tabs.sendMessage(tab.id, { type }).catch(() => null);
}
const settings = await getSettings();
term.value = settings.term;
showCount(await ask('getCount'));
const { lastCheck } = await chrome.storage.local.get('lastCheck');
if (lastCheck) document.getElementById('last-check').textContent = t('lastCheck', [new Date(lastCheck).toLocaleTimeString()]);
document.getElementById('highlight').addEventListener('click', async () => {
await saveSettings({ term: term.value });
showCount(await ask('highlight'));
});
term.addEventListener('keydown', (e) => {
if (e.key === 'Enter') document.getElementById('highlight').click();
});
document.getElementById('options').addEventListener('click', (e) => {
e.preventDefault();
chrome.runtime.openOptionsPage();
});