Skip to content

Commit

Permalink
Add background script
Browse files Browse the repository at this point in the history
  • Loading branch information
thanhlmm committed Aug 10, 2022
1 parent 707adfa commit 245909c
Show file tree
Hide file tree
Showing 9 changed files with 196 additions and 18 deletions.
5 changes: 5 additions & 0 deletions auto-imports.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Generated by 'unplugin-auto-import'
export {}
declare global {
const browser: typeof import('webextension-polyfill')['default']
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"svelte-preprocess": "^4.9.8",
"tslib": "^2.3.1",
"typescript": "^4.4.4",
"unplugin-auto-import": "^0.11.1",
"vite": "~2.9.0",
"web-ext": "^6.6.0"
},
Expand All @@ -38,8 +39,8 @@
"numeral": "^2.0.6",
"svelte-windicss-preprocess": "^4.2.8",
"tippy.js": "^6.3.7",
"vite-imagetools": "^4.0.4",
"url-pattern": "^1.0.3",
"vite-imagetools": "^4.0.4",
"webext-bridge": "^5.0.5",
"webextension-polyfill": "^0.9.0",
"windicss": "^3.5.6"
Expand Down
40 changes: 39 additions & 1 deletion src/entries/background/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
import browser from "webextension-polyfill";
import * as browser from "webextension-polyfill";
import { onMessage } from "webext-bridge";

browser.runtime.onInstalled.addListener(() => {
console.log("Extension installed");
});

console.log(browser);

const fetchBasicData = async () => {
const list = await fetch("https://api.coingecko.com/api/v3/search").then(
(response) => response.json()
);
console.log(browser.storage);
browser.storage.local
.set({ coinList: JSON.stringify(list.coins) })
.then(() => {
console.log("Loaded crypto list");
});
};

browser.runtime.onStartup.addListener(async () => {
console.log("onStartup....");
await fetchBasicData();
});

interface ICoinListInput {
limit: number;
}

onMessage<ICoinListInput, any>("coinList", async ({ data: { limit } }) => {
try {
const data = JSON.parse(
(await browser.storage.local.get("coinList")).coinList
);
return data.slice(0, limit);
} catch (error) {
return [];
}
});

// Run on init
fetchBasicData();
22 changes: 13 additions & 9 deletions src/entries/contentScript/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */
// import { onMessage, sendMessage } from "webext-bridge";
// import browser from "webextension-polyfill";
import * as browser from "webextension-polyfill";
import Mark from "mark.js";
import "@webcomponents/webcomponentsjs/webcomponents-bundle.js";
import { coinGeko } from "./views/network";
Expand All @@ -11,6 +11,7 @@ import "./views/AddressHighlight.svelte";
import "./views/TrxHighlight.svelte";
import "./views/NativeTokenHighlight.svelte";
import { escapeRegex } from "./views/utils";
import { sendMessage } from "webext-bridge";

const regexETHTrx = /0x[a-fA-F0-9]{64}/g; // TODO: Ignore longer address
const regexETHAddress = /0x[a-fA-F0-9]{40}/g; // TODO: Solana, Near regex
Expand Down Expand Up @@ -90,19 +91,24 @@ const getCoinList = async () => {

// Firefox `browser.tabs.executeScript()` requires scripts return a primitive value
(async () => {
// const coinList: { [key: string]: string | number }[] =
// (await sendMessage("coinList", { limit: 500 })) || [];
const coinList: { [key: string]: string | number }[] =
(await sendMessage("coinList", { limit: 500 })) || [];

const coinList = (await getCoinList()) || [];
console.log(coinList);

// const coinList = (await getCoinList()) || [];

const nameAndSymbolList: string[] = [
...coinList.map((item: any) => item.symbol.toUpperCase()),
];

const regexNativeToken = new RegExp(
`\\b(${nameAndSymbolList.slice(0, 500).map(function (w) {
return escapeRegex(w);
}).join("|")})\\b`,
`\\b(${nameAndSymbolList
.slice(0, 500)
.map(function (w) {
return escapeRegex(w);
})
.join("|")})\\b`,
"g"
);

Expand Down Expand Up @@ -205,8 +211,6 @@ const getCoinList = async () => {
data.symbol === item.innerText || data.name === item.innerText
);

console.log("selectedItem: ", selectedItem)

// Inject address as props
item.setAttribute("id", selectedItem?.id);
item.setAttribute("name", item.innerText);
Expand Down
2 changes: 1 addition & 1 deletion src/entries/options/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<body>
<div id="app"></div>
<script type="module" src="./main.ts"></script>
<!-- <script type="module" src="./main.ts"></script> -->
<nimbus-options />
</body>

Expand Down
2 changes: 1 addition & 1 deletion src/entries/popup/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<body style="min-width: 100px">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
<!-- <script type="module" src="./main.ts"></script> -->
<nimbus-popup />
</body>

Expand Down
3 changes: 2 additions & 1 deletion src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const sharedManifest = {
page: "src/entries/options/index.html",
open_in_tab: true,
},
permissions: [],
permissions: ["tabs", "storage", "activeTab", "http://*/", "https://*/"],
};

const browserAction = {
Expand Down Expand Up @@ -55,6 +55,7 @@ const ManifestV3 = {
action: browserAction,
background: {
service_worker: "src/entries/background/serviceWorker.ts",
type: "module",
},
host_permissions: ["*://*/*"],
};
Expand Down
18 changes: 17 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import path from "path";
import { getManifest } from "./src/manifest";
import { windi } from "svelte-windicss-preprocess";
import sveltePreprocess from "svelte-preprocess";
import AutoImport from "unplugin-auto-import/vite";

console.log({ env: process.env.NODE_ENV });

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
Expand All @@ -14,19 +17,32 @@ export default defineConfig(({ mode }) => {
plugins: [
svelte({
preprocess: [sveltePreprocess(), windi({})],
exclude: ["*.normal.svelte"],
// exclude: ["*.normal.svelte"],
compilerOptions: {
customElement: true,
},
}),
webExtension({
manifest: getManifest(Number(env.MANIFEST_VERSION)),
}),
AutoImport({
imports: [
{
"webextension-polyfill": [["default", "browser"]],
},
],
}),
],
resolve: {
alias: {
"~": path.resolve(__dirname, "./src"),
},
},
build: {
sourcemap: true, // TODO: Change me for prod build
},
optimizeDeps: {
include: ["webextension-polyfill"],
},
};
});
Loading

0 comments on commit 245909c

Please sign in to comment.