82 lines
2.5 KiB
JavaScript
82 lines
2.5 KiB
JavaScript
// Background Service Worker
|
|
import { backgroundHandler } from '../shared/messaging.js';
|
|
import { dictionaryManager, bingDictionary, youdaoDictionary } from '../shared/dictionary/index.js';
|
|
|
|
console.log('[SaladDict] Background service worker started');
|
|
|
|
// 监听安装事件
|
|
chrome.runtime.onInstalled.addListener((details) => {
|
|
console.log('[SaladDict] Extension installed:', details.reason);
|
|
});
|
|
|
|
// BackgroundHandler 自动初始化消息监听
|
|
console.log('[SaladDict] Message handler initialized');
|
|
|
|
// 注册词典到管理器
|
|
dictionaryManager.register('bing', bingDictionary);
|
|
dictionaryManager.register('youdao', youdaoDictionary);
|
|
console.log('[SaladDict] Registered dictionaries:', dictionaryManager.getNames());
|
|
|
|
// 注册词典查询处理器
|
|
backgroundHandler.register('DICT.SEARCH', async (payload) => {
|
|
const { word, dictNames = [] } = payload;
|
|
|
|
console.log('[Background] DICT.SEARCH:', word, dictNames);
|
|
|
|
try {
|
|
const { results, errors } = await dictionaryManager.search(word, dictNames);
|
|
|
|
console.log('[Background] Search results:', results);
|
|
if (errors.length > 0) {
|
|
console.warn('[Background] Search errors:', errors);
|
|
}
|
|
|
|
return { results, errors };
|
|
} catch (error) {
|
|
console.error('[Background] Search failed:', error);
|
|
throw error;
|
|
}
|
|
});
|
|
|
|
// 注册获取词典列表处理器
|
|
backgroundHandler.register('DICT.GET_LIST', async () => {
|
|
const dictionaries = dictionaryManager.getAll().map(({ name, dictionary }) => ({
|
|
name,
|
|
info: dictionary.getInfo()
|
|
}));
|
|
|
|
return { dictionaries };
|
|
});
|
|
|
|
// 注册 HTTP 请求处理器
|
|
backgroundHandler.register('HTTP.GET', async (payload) => {
|
|
const { url, options = {} } = payload;
|
|
|
|
console.log('[Background] HTTP.GET:', url);
|
|
|
|
try {
|
|
const response = await fetch(url, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.0',
|
|
...options.headers
|
|
},
|
|
...options
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
const text = await response.text();
|
|
return { text, status: response.status };
|
|
} catch (error) {
|
|
console.error('[Background] HTTP.GET failed:', error);
|
|
throw new Error(`请求失败: ${error.message}`);
|
|
}
|
|
});
|
|
|
|
console.log('[SaladDict] Message handlers registered');
|