chore: add chrome extension codes

This commit is contained in:
Steven
2022-09-13 22:34:13 +08:00
parent dfc797fe58
commit 48fb6018c0
6 changed files with 107 additions and 1 deletions

40
extension/background.js Normal file
View File

@@ -0,0 +1,40 @@
const getCorgiData = () => {
return new Promise((resolve) => {
chrome.storage.local.get(["corgi"], (data) => {
resolve(data?.corgi);
});
});
};
const fetchShortcut = async (name) => {
const corgiData = await getCorgiData();
if (corgiData.domain && corgiData.openId) {
const res = await fetch(`${corgiData.domain}/api/shortcut?openId=${corgiData.openId}&name=${name}`);
const { data } = await res.json();
if (data.length > 0) {
return data[0];
}
}
};
const urlRegex = /https?:\/\/go\/(.+)/;
chrome.tabs.onUpdated.addListener(async (_, a, tab) => {
if (typeof tab.url === "string") {
const matchResult = urlRegex.exec(tab.url);
if (matchResult) {
const name = matchResult[1];
const shortcut = await fetchShortcut(name);
if (shortcut && shortcut.link) {
chrome.tabs.update({ url: shortcut.link });
}
}
}
});
chrome.omnibox.onInputEntered.addListener(async (text) => {
const shortcut = await fetchShortcut(text);
if (shortcut && shortcut.link) {
chrome.tabs.update({ url: shortcut.link });
}
});