fangs/source/background-scripts/initialize.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-03-14 09:58:47 +00:00
import browser from 'webextension-polyfill';
import Bang, {type BangParameters} from '../bang/bang.js';
2022-03-14 09:58:47 +00:00
async function browserActionClicked() {
2022-03-14 09:58:47 +00:00
await browser.runtime.openOptionsPage();
}
if (import.meta.env.VITE_BROWSER === 'chromium') {
browser.action.onClicked.addListener(browserActionClicked);
} else {
browser.browserAction.onClicked.addListener(browserActionClicked);
}
2022-03-14 09:58:47 +00:00
browser.runtime.onInstalled.addListener(async () => {
if (import.meta.env.DEV) {
await browser.runtime.openOptionsPage();
}
});
browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
const detailsUrl = new URL(details.url);
2022-12-05 13:39:14 +00:00
const supportedHosts = ['duckduckgo.com', 'google.com'];
if (supportedHosts.includes(detailsUrl.host)) {
2022-03-14 09:58:47 +00:00
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.local.get(id);
if (data[id] === undefined) {
return;
}
const bang = Bang.parseParameters(qParameter, data[id] as BangParameters);
await browser.tabs.update({url: bang.destination});
});