AI 工具开发实战(5):开发一个 AI 浏览器划词翻译插件——Chrome 扩展开发入门

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": ["<all_urls>"],
    "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 < 2) {
    removeBubble();
    return;
  }

  // 检测是否是英文
  if (!/[a-zA-Z]/.test(selectedText)) {
    removeBubble();
    return;
  }

  showBubble(e.pageX, e.pageY, '⏳ 翻译中...');

  try {
    const { translate } = await import(chrome.runtime.getURL('translator.js'));
    const result = await translate(selectedText);
    showBubble(e.pageX, e.pageY, result);
  } catch (err) {
    showBubble(e.pageX, e.pageY, '翻译失败,请检查 API Key');
  }
});

function showBubble(x, y, text) {
  removeBubble();
  bubble = document.createElement('div');
  bubble.className = 'ai-trans-bubble';
  bubble.innerHTML = `
    <div class="ai-trans-content">${escapeHtml(text)}</div>
    <div class="ai-trans-actions">
      <button class="ai-trans-copy">📋 复制</button>
    </div>
  `;
  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;
}

弹出窗口(设置页面)

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><style>
  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; }
</style></head>
<body>
  <h2>🤖 AI 划词翻译</h2>
  <input type="password" id="apiKey" placeholder="DeepSeek API Key (sk-...)">
  <button id="save">保存</button>
  <div id="status"></div>
  <p>选中网页上的英文 → 自动翻译</p>
  <script src="popup.js"></script>
</body>
</html>
// 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 周报自动生成器


如果觉得有用,欢迎 点赞 + 收藏 + 关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天风之翼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值