AI 工具开发实战(5):开发一个 AI 浏览器划词翻译插件——Chrome 扩展开发入门
前几篇都是 CLI 和编辑器工具,这篇做一个浏览器插件——选中网页上的文字,弹出翻译结果。
用 Chrome Extension Manifest V3,调用 DeepSeek API 做翻译。
插件做什么
浏览英文网页 → 选中文字 → 弹出翻译气泡 → 显示中文翻译
项目结构
ai-translate-extension/
├── manifest.json # 插件配置
├── popup.html # 弹出窗口
├── popup.js # 弹出窗口逻辑
├── content.js # 注入页面的脚本(划词翻译)
├── translator.js # AI 翻译
├── styles.css # 样式
└── icons/ # 图标
manifest.json
{
"manifest_version": 3,
"name": "AI 划词翻译",
"version": "1.0",
"description": "选中文字,AI 自动翻译",
"permissions": ["storage"],
"host_permissions": ["https://api.deepseek.com/*"],
"action": {
"default_popup": "popup.html",
"default_icon": "icons/icon48.png"
},
"content_scripts": [{
"matches": [""],
"js": ["content.js"],
"css": ["styles.css"]
}],
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
AI 翻译模块
// translator.js
async function translate(text, targetLang = '中文') {
const apiKey = await getApiKey();
if (!apiKey) return '请先在插件设置中配置 API Key';
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{ role: 'system', content: `只输出翻译结果,不要解释。目标语言:${targetLang}。` },
{ role: 'user', content: text },
],
temperature: 0.1,
max_tokens: Math.min(text.length * 2, 2048),
}),
});
const data = await response.json();
return data.choices[0].message.content.trim();
}
async function getApiKey() {
const result = await chrome.storage.sync.get(['apiKey']);
return result.apiKey || '';
}
页面注入脚本(划词翻译核心)
// content.js
let bubble = null;
document.addEventListener('mouseup', async (e) => {
const selectedText = window.getSelection().toString().trim();
if (!selectedText || selectedText.length ${escapeHtml(text)}
📋 复制
`;
bubble.style.cssText = `
position: fixed;
left: ${x + 10}px;
top: ${y + 10}px;
z-index: 999999;
max-width: 400px;
background: #1e293b;
color: #e2e8f0;
padding: 12px 16px;
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
`;
document.body.appendChild(bubble);
// 复制按钮
bubble.querySelector('.ai-trans-copy').onclick = () => {
navigator.clipboard.writeText(text);
bubble.querySelector('.ai-trans-copy').textContent = '✅ 已复制';
};
// 点击其他地方关闭
setTimeout(() => {
document.addEventListener('click', closeBubble, { once: true });
}, 100);
}
function closeBubble(e) {
if (bubble && !bubble.contains(e.target)) {
removeBubble();
}
}
function removeBubble() {
if (bubble) {
bubble.remove();
bubble = null;
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
弹出窗口(设置页面)
body { width: 300px; padding: 16px; font-family: sans-serif; }
h2 { font-size: 16px; margin: 0 0 12px; }
input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px; font-size: 13px; }
button { width: 100%; margin-top: 8px; padding: 8px; background: #2563eb; color: white; border: none; border-radius: 6px; cursor: pointer; }
#status { margin-top: 8px; font-size: 12px; color: #22c55e; }
p { font-size: 11px; color: #9ca3af; margin-top: 12px; }
🤖 AI 划词翻译
保存
选中网页上的英文 → 自动翻译
// popup.js
document.addEventListener('DOMContentLoaded', async () => {
const result = await chrome.storage.sync.get(['apiKey']);
if (result.apiKey) {
document.getElementById('apiKey').value = result.apiKey;
document.getElementById('status').textContent = '✅ 已配置';
}
document.getElementById('save').onclick = async () => {
const key = document.getElementById('apiKey').value.trim();
if (!key.startsWith('sk-')) {
document.getElementById('status').textContent = '❌ Key 格式错误';
return;
}
await chrome.storage.sync.set({ apiKey: key });
document.getElementById('status').textContent = '✅ 已保存';
};
});
安装使用
# 1. 打开 Chrome → chrome://extensions/
# 2. 打开"开发者模式"
# 3. 点击"加载已解压的扩展程序"
# 4. 选择 ai-translate-extension 文件夹
# 5. 点击插件图标 → 输入 DeepSeek API Key
# 6. 浏览任意网页,选中英文文字 → 弹出翻译
效果
浏览英文技术文档 → 选中 "Transformer architecture enables parallel processing"
→ 浮动气泡显示:"Transformer 架构实现了并行处理"
→ 点击「复制」→ 译文复制到剪贴板
成本
一次翻译约消耗 50-200 token,费用不到 1 分钱。日常使用一个月只要几块钱。
总结
Chrome 插件的核心就三步:
1. content.js 注入页面 → 监听 mouseup 事件
2. 获取选中文字 → 调用 LLM API
3. 动态创建一个 div 浮动气泡显示结果
配合 chrome.storage.sync 做 Key 管理,一个实用的浏览器 AI 插件就完成了。
本文是 《AI 开发者工具链实战》 系列的第 5 篇。
上一篇:VS Code AI 插件
下一篇:AI 周报自动生成器
本文由 Zyentor(智元界)原创发布