fangs/source/background-scripts/initialize.ts

56 lines
1.4 KiB
TypeScript

import browser from 'webextension-polyfill';
import Bang, {type BangParameters} from '../bang/bang.js';
async function browserActionClicked() {
await browser.runtime.openOptionsPage();
}
if (import.meta.env.VITE_BROWSER === 'chromium') {
browser.action.onClicked.addListener(browserActionClicked);
} else {
browser.browserAction.onClicked.addListener(browserActionClicked);
}
browser.runtime.onInstalled.addListener(async () => {
if (import.meta.env.DEV) {
await browser.runtime.openOptionsPage();
}
const {dataVersion} = await browser.storage.sync.get({
dataVersion: '0',
});
if (dataVersion === '0') {
const local = await browser.storage.local.get();
local.dataVersion = '1';
await browser.storage.sync.set(local);
}
});
browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
const detailsUrl = new URL(details.url);
const supportedHosts = ['duckduckgo.com', 'google.com'];
if (supportedHosts.includes(detailsUrl.host)) {
return;
}
const qParameter = detailsUrl.searchParams.get('q') ?? undefined;
if (qParameter === undefined) {
return;
}
const id = Bang.parseId(qParameter);
if (id === undefined) {
return;
}
const data = await browser.storage.sync.get(id);
if (data[id] === undefined) {
return;
}
const bang = Bang.parseParameters(qParameter, data[id] as BangParameters);
await browser.tabs.update({url: bang.destination});
});