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

Chrome扩展Manifest V3获取用户选中文本及修复chrome.action未定义问题

Chrome扩展Manifest V3实现点击图标弹窗显示选中文字

问题根源

  1. chrome.action未定义:chrome.action.onClicked仅支持在后台服务工作者(Service Worker)或扩展弹窗页面中使用,content script无该API权限,因此在content.js中监听会触发报错。
  2. DOM访问限制:Manifest V3的后台脚本是无DOM环境的Service Worker,无法直接操作标签页DOM,必须通过chrome.scripting.executeScript向目标标签页注入脚本,在标签页自身上下文内获取选中文本。

修正后的代码实现

方案一:动态注入脚本(轻量版)

无需提前注入content script,仅在点击图标时执行一次逻辑。

manifest.json

{
  "name": "Selected text alert",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "点击显示选中的文本"
  },
  "permissions": ["activeTab", "scripting"]
}

background.js

chrome.action.onClicked.addListener(async (tab) => {
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: () => {
      const selectedText = document.getSelection().toString();
      alert(selectedText || "未选中任何文本");
    }
  });
});

方案二:content script配合消息传递(适合复杂逻辑)

如果需要在content script中复用更多业务逻辑,可采用消息传递触发操作。

manifest.json

{
  "name": "Selected text alert",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "点击显示选中的文本"
  },
  "permissions": ["activeTab", "scripting"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

background.js

chrome.action.onClicked.addListener(async (tab) => {
  await chrome.tabs.sendMessage(tab.id, { action: "showSelectedText" });
});

content.js

chrome.runtime.onMessage.addListener((message) => {
  if (message.action === "showSelectedText") {
    const selectedText = document.getSelection().toString();
    alert(selectedText || "未选中任何文本");
  }
});

说明

  • 动态注入脚本的方式更轻量,仅在用户触发操作时执行代码,避免不必要的资源占用。
  • 消息传递方案适合需要在content script中处理复杂DOM交互或状态管理的场景。
  • 两种方案均在标签页自身上下文内执行document.getSelection(),完全符合Manifest V3的权限规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:44:53