/** * 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();