Files
store_ai_extension/src/background/index.ts
2026-05-06 10:22:38 +08:00

36 lines
1.0 KiB
TypeScript

import { handleBackgroundCommand, handleInstalled, handleStartup, handleWindowRemoved } from './service';
import type { BackgroundCommand } from './types';
chrome.runtime.onInstalled.addListener(() => {
void handleInstalled();
});
chrome.runtime.onStartup.addListener(() => {
void handleStartup();
});
chrome.runtime.onMessage.addListener((message: BackgroundCommand, _sender, sendResponse) => {
void handleBackgroundMessage(message, sendResponse);
return true;
});
chrome.windows.onRemoved.addListener((windowId) => {
void handleWindowRemoved(windowId);
});
/**
* 统一包装后台消息处理,确保异步错误能回给调用方。
*/
async function handleBackgroundMessage(
message: BackgroundCommand,
sendResponse: (response?: unknown) => void,
) {
try {
const result = await handleBackgroundCommand(message);
sendResponse(result);
} catch (error: unknown) {
const messageText = error instanceof Error ? error.message : 'Unknown error';
sendResponse({ ok: false, error: messageText });
}
}