Skip to content

Commit 143d1cc

Browse files
authored
Adding service worker heartbeat (#52)
1 parent 1df8929 commit 143d1cc

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

src/background/heartbeat.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copied from https://developer.chrome.com/docs/extensions/develop/migrate/to-service-workers?hl=pt-br#keep_a_service_worker_alive_continuously
2+
3+
import log from "loglevel";
4+
import { storage } from "webextension-polyfill";
5+
6+
/**
7+
* Starts the heartbeat interval which keeps the service worker alive. Call
8+
* this sparingly when you are doing work which requires persistence, and call
9+
* stopHeartbeat once that work is complete.
10+
*/
11+
export async function startHeartbeat() {
12+
// Run the heartbeat once at service worker startup.
13+
runHeartbeat().then(() => {
14+
// Then again every 20 seconds.
15+
setInterval(runHeartbeat, 20000);
16+
});
17+
}
18+
19+
async function runHeartbeat() {
20+
log.debug("Heartbeat", getLastHeartbeat());
21+
try {
22+
await storage.local.set({
23+
"last-heartbeat": Date.now().toString(),
24+
});
25+
} catch (err: any) {
26+
log.error("Heartbeat error", err);
27+
}
28+
}
29+
30+
/**
31+
* Returns the last heartbeat stored in extension storage, or undefined if
32+
* the heartbeat has never run before.
33+
*/
34+
async function getLastHeartbeat() {
35+
return (await storage.local.get("last-heartbeat"))["last-heartbeat"];
36+
}

src/background/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { action, type Runtime, runtime } from "webextension-polyfill";
33
import { ArrayQueue, ConstantBackoff, WebsocketBuilder } from "websocket-ts";
44

55
import { defaultSettings, loadSettings, type Settings } from "#/settings";
6+
import { startHeartbeat } from "./heartbeat";
67

78
// init on load
89
(async () => init())();
@@ -13,6 +14,7 @@ let settings: Settings = defaultSettings;
1314
* Loads the current settings, and listens for incoming connections (from the injected contentscript)
1415
*/
1516
async function init() {
17+
startHeartbeat();
1618
settings = await loadSettings();
1719
log.setLevel(settings.logLevel);
1820

src/inpage/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ import { name } from "./utils";
88

99
const { PROD } = import.meta.env;
1010

11-
// @ts-ignore
11+
// @ts-expect-error
1212
import iconProd from "../public/icons/ethui-black.svg?base64";
13-
// @ts-ignore
13+
// @ts-expect-error
1414
import iconDev from "../public/icons/ethui-purple.svg?base64";
1515

1616
const icon = PROD ? iconProd : iconDev;

0 commit comments

Comments
 (0)