Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 67 additions & 61 deletions entrypoints/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ async function translateWithMicrosoftInBackground(text: string, targetLang: stri
try {
// 获取微软翻译的JWT令牌
const jwtToken = await refreshMicrosoftTokenInBackground();

// 调用微软翻译API
const response = await fetch(`https://api-edge.cognitive.microsofttranslator.com/translate?from=&to=${targetLang}&api-version=3.0&includeSentenceLength=true&textType=html`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jwtToken
},
body: JSON.stringify([{Text: text}])
body: JSON.stringify([{ Text: text }])
});

if (response.ok) {
Expand Down Expand Up @@ -57,77 +57,83 @@ export default defineBackground({
safari: false,
},
main() {
const isContextMenuSupported = !!browser.contextMenus

// 创建右键菜单项
try {
// 创建父菜单
browser.contextMenus.create({
id: 'fluentread-parent',
title: 'FluentRead',
contexts: ['page', 'selection'],
});

// 创建全文翻译子菜单
browser.contextMenus.create({
id: CONTEXT_MENU_IDS.TRANSLATE_FULL_PAGE,
title: '全文翻译',
parentId: 'fluentread-parent',
contexts: ['page', 'selection'],
});

// 创建撤销翻译子菜单
browser.contextMenus.create({
id: CONTEXT_MENU_IDS.RESTORE_ORIGINAL,
title: '撤销翻译',
parentId: 'fluentread-parent',
contexts: ['page', 'selection'],
enabled: false, // 初始状态为禁用
});
} catch (error) {
console.error('Error setting up context menu:', error);
}
if (isContextMenuSupported) {
try {
// 创建父菜单
browser.contextMenus.create({
id: 'fluentread-parent',
title: 'FluentRead',
contexts: ['page', 'selection'],
});

// 创建全文翻译子菜单
browser.contextMenus.create({
id: CONTEXT_MENU_IDS.TRANSLATE_FULL_PAGE,
title: '全文翻译',
parentId: 'fluentread-parent',
contexts: ['page', 'selection'],
});

// 监听右键菜单点击事件
browser.contextMenus.onClicked.addListener((info: any, tab: any) => {
if (!tab?.id) return;

if (info.menuItemId === CONTEXT_MENU_IDS.TRANSLATE_FULL_PAGE) {
// 发送消息到内容脚本触发全文翻译
browser.tabs.sendMessage(tab.id, {
type: 'contextMenuTranslate',
action: 'fullPage'
}).then(() => {
// 更新翻译状态
translationStateMap.set(tab.id!, true);
updateContextMenus(tab.id!);
}).catch((error: any) => {
console.error('Failed to send message to content script:', error);
// 创建撤销翻译子菜单
browser.contextMenus.create({
id: CONTEXT_MENU_IDS.RESTORE_ORIGINAL,
title: '撤销翻译',
parentId: 'fluentread-parent',
contexts: ['page', 'selection'],
enabled: false, // 初始状态为禁用
});
} else if (info.menuItemId === CONTEXT_MENU_IDS.RESTORE_ORIGINAL) {
// 发送消息到内容脚本撤销翻译
browser.tabs.sendMessage(tab.id, {
type: 'contextMenuTranslate',
action: 'restore'
}).then(() => {
// 更新翻译状态
translationStateMap.set(tab.id!, false);
updateContextMenus(tab.id!);
}).catch((error: any) => {
console.error('Failed to send message to content script:', error);

// 监听右键菜单点击事件
browser.contextMenus.onClicked.addListener((info: any, tab: any) => {
if (!tab?.id) return;

if (info.menuItemId === CONTEXT_MENU_IDS.TRANSLATE_FULL_PAGE) {
// 发送消息到内容脚本触发全文翻译
browser.tabs.sendMessage(tab.id, {
type: 'contextMenuTranslate',
action: 'fullPage'
}).then(() => {
// 更新翻译状态
translationStateMap.set(tab.id!, true);
updateContextMenus(tab.id!);
}).catch((error: any) => {
console.error('Failed to send message to content script:', error);
});
} else if (info.menuItemId === CONTEXT_MENU_IDS.RESTORE_ORIGINAL) {
// 发送消息到内容脚本撤销翻译
browser.tabs.sendMessage(tab.id, {
type: 'contextMenuTranslate',
action: 'restore'
}).then(() => {
// 更新翻译状态
translationStateMap.set(tab.id!, false);
updateContextMenus(tab.id!);
}).catch((error: any) => {
console.error('Failed to send message to content script:', error);
});
}
});

} catch (error) {
console.error('Error setting up context menu:', error);
}
});
} else {
console.log("不支持右键菜单")
}

// 更新右键菜单状态
const updateContextMenus = (tabId: number) => {
const isTranslated = translationStateMap.get(tabId) || false;

try {
// 更新全文翻译菜单项
browser.contextMenus.update(CONTEXT_MENU_IDS.TRANSLATE_FULL_PAGE, {
enabled: !isTranslated,
title: isTranslated ? '全文翻译 (已翻译)' : '全文翻译'
});

// 更新撤销翻译菜单项
browser.contextMenus.update(CONTEXT_MENU_IDS.RESTORE_ORIGINAL, {
enabled: isTranslated,
Expand All @@ -140,15 +146,15 @@ export default defineBackground({

// 监听标签页切换事件,更新菜单状态
browser.tabs.onActivated.addListener((activeInfo: any) => {
updateContextMenus(activeInfo.tabId);
if (isContextMenuSupported) updateContextMenus(activeInfo.tabId);
});

// 监听标签页更新事件(页面刷新等)
browser.tabs.onUpdated.addListener((tabId: any, changeInfo: any) => {
if (changeInfo.status === 'complete') {
// 页面加载完成,重置翻译状态
translationStateMap.set(tabId, false);
updateContextMenus(tabId);
if (isContextMenuSupported) updateContextMenus(tabId);
}
});

Expand All @@ -167,7 +173,7 @@ export default defineBackground({
resolve({ success: true, translatedText });
return;
}

// 处理普通翻译请求
_service[config.service](message)
.then(resp => resolve(resp)) // 成功
Expand Down