summaryrefslogtreecommitdiff
path: root/src/background/index.js
blob: 8e3c5f10cf0771f6281bdfe8961920859e079b95 (plain)
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
/**
 * Background entry point (Firefox MV3 event page, ES module).
 *
 * All event listeners are registered synchronously at the top level so the
 * event page can be woken by any of them (MDN: background scripts).
 */

import { registerRuntimeMessageHandler, handleConnection, handlePopupStateConnection } from './message-router.js';
import { loadSettings, watchSettings } from './settings-service.js';
import { startFromSelection } from './menu-translation.js';

// One-shot messages from popup / options.
registerRuntimeMessageHandler();

// Streaming connections from the content script.
browser.runtime.onConnect.addListener(handleConnection);

// Live translation state updates for the popup (translation result mode).
browser.runtime.onConnect.addListener(handlePopupStateConnection);

// Selection context menu (works on normal pages and the PDF Viewer).
if (browser.menus && typeof browser.menus.create === 'function') {
  browser.menus.create({
    id: 'translate-selection',
    title: '選択したテキストを翻訳',
    contexts: ['selection']
  });
  browser.menus.onClicked.addListener((info) => {
    if (!info || info.menuItemId !== 'translate-selection') return;
    const result = startFromSelection(info.selectionText);
    if (result.ok) {
      // Open the toolbar popup as the result UI. openPopup() must be called
      // synchronously within the click user gesture. It can reject when the
      // popup is already open or on unsupported platforms - ignore safely.
      try {
        const p = browser.action.openPopup();
        if (p && typeof p.catch === 'function') {
          p.catch(() => {});
        }
      } catch {
        // openPopup unavailable; the user can open the popup manually
      }
    }
  });
}

// Keep the validated settings cache in sync and load initial settings.
watchSettings();
void loadSettings();