如何创建整页法语翻译Chrome扩展?现有代码故障求助
解决方案:修复网页法语翻译Chrome扩展并配置快捷键
一、修正后台脚本(background.js)的问题
原代码存在上下文错误、依赖缺失等关键问题,以下是修复后的完整代码:
// 初始化扩展徽章状态 chrome.runtime.onInstalled.addListener(() => { chrome.action.setBadgeText({ text: "OFF", }); }); // 点击图标触发翻译/还原 chrome.action.onClicked.addListener(async (tab) => { if (!tab.url || tab.url.startsWith('chrome://')) return; // 排除Chrome内置页面 const prevState = await chrome.action.getBadgeText({ tabId: tab.id }); const nextState = prevState === 'ON' ? 'OFF' : 'ON'; await chrome.action.setBadgeText({ tabId: tab.id, text: nextState, }); if (nextState === "ON") { await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { // 移除已有的翻译元素,避免重复添加 const existingTranslateEl = document.getElementById('google_translate_element'); if (existingTranslateEl) existingTranslateEl.remove(); // 设置页面源语言为英文 document.documentElement.setAttribute('lang', 'en'); // 创建翻译容器 const gt = document.createElement('div'); gt.id = "google_translate_element"; document.body.appendChild(gt); // 加载谷歌翻译脚本 const script = document.createElement("script"); script.type = "text/javascript"; script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"; document.body.appendChild(script); // 初始化翻译组件,指定目标语言为法语 window.googleTranslateElementInit = function() { new google.translate.TranslateElement( { pageLanguage: 'en', targetLanguage: 'fr', autoDisplay: false }, 'google_translate_element' ); // 强制触发翻译 setTimeout(() => { const translateButton = document.querySelector('.goog-te-combo')?.parentNode?.querySelector('button'); if (translateButton) translateButton.click(); }, 1000); }; }, }); } else if (nextState === "OFF") { await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { // 移除翻译元素和相关脚本 const translateEl = document.getElementById('google_translate_element'); if (translateEl) translateEl.remove(); const translateScripts = document.querySelectorAll('script[src*="translate.google.com"]'); translateScripts.forEach(script => script.remove()); // 重置页面语言并触发翻译还原 document.documentElement.setAttribute('lang', ''); const restoreButton = document.querySelector('.goog-te-banner-frame .goog-te-button'); if (restoreButton) restoreButton.click(); }, }); } });
关键修复点:
- 将
chrome.runtime.onInstalled移出点击回调,确保扩展安装时就初始化徽章状态 - 注入页面的函数包含所有依赖逻辑,避免跨上下文函数不可用的问题
- 添加重复元素移除逻辑,防止多次点击创建多个翻译组件
- 明确指定翻译目标语言为法语(
targetLanguage: 'fr') - 添加强制触发翻译和还原的逻辑
- 排除Chrome内置页面,避免脚本注入失败
二、配置manifest.json的快捷键(suggested_key)
在manifest.json中添加commands字段,配置触发扩展的快捷键,示例如下:
{ "manifest_version": 3, "name": "网页法语翻译器", "version": "1.0", "description": "一键将网页翻译成法语", "permissions": ["activeTab", "scripting"], "action": { "default_icon": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }, "background": { "service_worker": "background.js" }, "commands": { "_execute_action": { "suggested_key": { "default": "Ctrl+Shift+F", "mac": "Command+Shift+F" }, "description": "触发网页法语翻译/还原" } }, "icons": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }
配置说明:
_execute_action对应点击扩展图标的动作,配置快捷键后可通过按键触发相同功能suggested_key中的default对应Windows/Linux平台,mac对应Mac平台,可按需修改组合键
三、注意事项
- 确保使用Manifest V3版本(当前Chrome官方推荐标准)
- 准备对应尺寸的图标文件放在
icons目录,或移除icons字段使用默认图标 - 功能依赖谷歌翻译外部脚本,需保证用户网络可访问translate.google.com
内容的提问来源于stack exchange,提问作者ramin
相关产品推荐
相关产品推荐

