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

Firefox扩展开发:获取上下文菜单选中文本遇阻求解决方案

Firefox扩展获取选中文本的解决办法

一、原方案失效的核心原因

你直接用getSelection().toString()在Firefox里拿不到文本,大概率是因为在扩展的背景/弹出脚本里直接调用了这个方法——这类脚本运行在隔离的扩展上下文,无法访问当前页面的DOM选择器。正确姿势是往目标页面注入脚本,在页面上下文里获取文本:

Manifest V2 实现代码

// 背景脚本或弹出脚本中执行
browser.tabs.executeScript({
  code: "window.getSelection().toString();"
}).then(results => {
  const selectedText = results[0];
  if (selectedText) {
    // 拿到文本后执行你的翻译逻辑
    console.log(selectedText);
  }
}).catch(err => {
  console.error('获取选中文本失败:', err);
});

Manifest V3 实现代码

Manifest V3 需要改用scripting API,记得在manifest.json中添加scripting权限:

// 先获取当前活动标签页ID
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
  const tabId = tabs[0].id;
  browser.scripting.executeScript({
    target: {tabId: tabId},
    func: () => window.getSelection().toString()
  }).then(results => {
    const selectedText = results[0].result;
    // 执行翻译处理
  });
});

二、关于从右键谷歌搜索提取文本的备选方案

这个思路不推荐,兼容性极差:浏览器自带的右键菜单事件难以直接拦截,你需要监听点击后解析谷歌搜索的URL参数(搜索关键词即选中文本),还要处理URL编码解码,反而比注入脚本的方案更繁琐。

三、必加的权限配置

无论使用哪个Manifest版本,都需要在manifest.json中添加对应权限:

  • Manifest V2:添加"activeTab"或<all_urls>
  • Manifest V3:添加"activeTab"和"scripting"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:45:43