aboutsummaryrefslogtreecommitdiffstats
path: root/apps/browser-extension/src/background/background.ts
blob: 9c4604af76708a6127df814cb888bf1b4a8e5252 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {
  getPluginSettings,
  Settings,
  subscribeToSettingsChanges,
} from "../utils/settings.ts";

const OPEN_HOARDER_ID = "open-hoarder";

function checkSettingsState(settings: Settings) {
  if (settings?.address) {
    registerContextMenu();
  } else {
    chrome.contextMenus.remove(OPEN_HOARDER_ID);
  }
}

/**
 * Registers a context menu button to open a tab with the currently configured hoarder instance
 */
function registerContextMenu() {
  chrome.contextMenus.create({
    id: OPEN_HOARDER_ID,
    title: "Open Hoarder",
    contexts: ["action"],
  });
}

/**
 * Reads the current settings and opens a new tab with hoarder
 * @param info the information about the click in the context menu
 */
function handleContextMenuClick(info: chrome.contextMenus.OnClickData) {
  const { menuItemId } = info;
  if (menuItemId === OPEN_HOARDER_ID) {
    getPluginSettings().then((settings: Settings) => {
      chrome.tabs.create({ url: settings.address, active: true });
    });
  }
}

getPluginSettings().then((settings: Settings) => {
  checkSettingsState(settings);
});

subscribeToSettingsChanges((settings) => {
  checkSettingsState(settings);
});

chrome.contextMenus.onClicked.addListener(handleContextMenuClick);