feat: add chrome extension

This commit is contained in:
Steven 2023-07-11 08:37:27 +08:00
parent 28df6e35fb
commit 1cbab78989
6 changed files with 87 additions and 2 deletions

2
.gitignore vendored
View File

@ -11,5 +11,3 @@ web/dist
build build
.DS_Store .DS_Store
extension

21
extension/background.js Normal file
View File

@ -0,0 +1,21 @@
import { getShortifyData } from "./common.js";
const urlRegex = /https?:\/\/s\/(.+)/;
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (typeof tab.url === "string") {
const matchResult = urlRegex.exec(tab.url);
if (matchResult) {
const shortifyData = await getShortifyData();
const name = matchResult[1];
const url = `${shortifyData.domain}/s/${name}`;
return chrome.tabs.update({ url });
}
}
});
chrome.omnibox.onInputEntered.addListener(async (text) => {
const shortifyData = await getShortifyData();
const url = `${shortifyData.domain}/s/${text}`;
return chrome.tabs.update({ url });
});

11
extension/common.js Normal file
View File

@ -0,0 +1,11 @@
export const getShortifyData = () => {
return new Promise((resolve, reject) => {
chrome.storage.local.get(["shortify"], (data) => {
if (data?.shortify) {
resolve(data.shortify);
} else {
reject("shortify data not found");
}
});
});
};

18
extension/manifest.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "Shortify",
"description": "",
"version": "0.1.0",
"manifest_version": 3,
"omnibox": {
"keyword": "s/"
},
"action": {
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions": ["tabs", "activeTab", "storage"],
"host_permissions": ["*://s/*"]
}

14
extension/popup.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<body>
<h2>Shortify extension</h2>
<div>
<span>Domain</span>
<input id="domain-input" type="text" />
</div>
<div>
<button id="save-button">Save</button>
</div>
<script type="module" src="popup.js"></script>
</body>
</html>

23
extension/popup.js Normal file
View File

@ -0,0 +1,23 @@
import { getShortifyData } from "./common.js";
const saveButton = document.body.querySelector("#save-button");
const domainInput = document.body.querySelector("#domain-input");
saveButton.addEventListener("click", () => {
chrome.storage.local.set({
shortify: {
domain: domainInput.value,
},
});
});
(async () => {
try {
const shortifyData = await getShortifyData();
if (shortifyData) {
domainInput.value = shortifyData.domain;
}
} catch (error) {
// do nothing.
}
})();