You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现类似谷歌翻译扩展的用户选中内容获取功能?

实现类似谷歌翻译的选中内容捕获功能

要实现像谷歌翻译扩展那样捕获页面选中内容并触发交互的功能,核心是通过浏览器扩展的内容脚本监听页面的文本选中事件,以下是具体实现步骤:


1. 编写内容脚本(监听选中事件)

内容脚本会注入到所有目标页面中,负责监听用户的文本选中行为:

// content.js
let debounceTimer;

// 监听选中变化事件
document.addEventListener('selectionchange', () => {
  // 防抖处理,避免选中过程中频繁触发
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    const selection = window.getSelection();
    const selectedText = selection.toString().trim();

    // 忽略空选中或输入框内的选中
    if (!selectedText) return;
    const activeEl = document.activeElement;
    if (activeEl && ['INPUT', 'TEXTAREA'].includes(activeEl.tagName)) return;

    // 获取选中区域的位置信息
    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();

    // 渲染浮动交互面板
    renderSelectionPanel(selectedText, rect);
  }, 150);
});

// 创建并渲染选中内容面板
function renderSelectionPanel(text, rect) {
  // 移除已有面板
  const oldPanel = document.getElementById('selection-panel');
  if (oldPanel) oldPanel.remove();

  // 创建面板元素
  const panel = document.createElement('div');
  panel.id = 'selection-panel';
  panel.style.cssText = `
    position: absolute;
    top: ${rect.bottom + window.scrollY + 8}px;
    left: ${rect.left + window.scrollX}px;
    padding: 8px 16px;
    background: #ffffff;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    z-index: 999999;
    font-size: 14px;
  `;
  panel.innerHTML = `<span>选中内容:</span><strong>${text}</strong>`;

  // 添加到页面
  document.body.appendChild(panel);

  // 点击页面空白处关闭面板
  document.addEventListener('click', (e) => {
    if (!panel.contains(e.target)) panel.remove();
  }, { once: true });
}

2. 配置扩展清单文件(manifest.json)

需要在manifest.json中声明内容脚本的注入规则,确保脚本能作用到目标页面:

{
  "manifest_version": 3,
  "name": "选中内容捕获工具",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

3. 关键优化点

  • 防抖处理:避免用户拖动选中文本时频繁触发面板渲染
  • 输入框过滤:跳过输入框、文本域内的选中操作,避免干扰用户输入
  • 面板定位适配:可以额外处理面板超出视口的情况,比如当选中内容在页面底部时,将面板定位到选中区域上方
  • 交互扩展:如果需要实现翻译等功能,可通过chrome.runtime.sendMessage将选中文本传递给扩展后台,再调用对应接口返回结果更新面板

内容的提问来源于stack exchange,提问作者Catif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:15:18