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

Chrome扩展右键菜单复制内容至剪贴板失败问题求助

问题分析与解决方案

错误原因

你遇到的TypeError: Cannot read properties of undefined (reading 'writeText'),核心原因是Manifest V3的后台脚本运行在Service Worker环境中,这个环境不存在navigator.clipboard对象;而普通网页属于浏览器常规上下文,支持该API,所以测试网页里代码能正常运行,但扩展后台不行。

解决步骤

1. 补充Manifest权限

在manifest.json的permissions数组中添加scripting和activeTab权限,确保扩展能向当前标签页注入脚本:

{
  "permissions": ["contextMenus", "notifications", "scripting", "activeTab"]
}

2. 修改后台脚本的复制逻辑

把直接调用navigator.clipboard.writeText的代码,替换为通过chrome.scripting.executeScript向当前活跃标签页注入脚本,在标签页上下文执行剪贴板操作,同时修复原代码中字符串拼接的逻辑问题:

chrome.runtime.onMessage.addListener(data => {
  if (data.type === 'notification') {
    CBC(data.message);
  }
});

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'CBC',
    title: "Create Beyond20 Command", 
    contexts: ["selection", "link", "image", "video"]
  });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if ('CBC' === info.menuItemId) {
    // 确定要使用的内容优先级
    let content = info.selectionText || info.linkUrl || info.srcUrl || 'error';
    // 构造最终复制的命令文本
    let copyText = `[[after]] [name](${content})[[/after]]`;
    
    // 触发通知
    CBC(content);

    // 向当前标签页注入脚本执行剪贴板写入
    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: (text) => {
          navigator.clipboard.writeText(text);
        },
        args: [copyText]
      });
    } catch (err) {
      console.error('复制失败:', err);
    }
  }
});

const CBC = message => { 
  return chrome.notifications.create('', {
    type: 'basic',
    title: 'Command Created',
    message: `[[after]] [name](${message})[[/after]]` || 'error',
    iconUrl: './assets/icons/128.png',
  });
};

关键说明

  • Service Worker限制:Manifest V3的后台不再是普通页面,无法直接访问DOM和部分网页API(如navigator.clipboard),必须通过注入脚本到标签页的方式实现相关操作。
  • executeScript作用:该API允许扩展向指定标签页注入函数和参数,在标签页的常规上下文执行,这里就能正常使用navigator.clipboard了。
  • 异步处理:chrome.scripting.executeScript返回Promise,所以需要用async/await处理异步逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:20:16