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

点击Chrome扩展图标/弹窗按钮时注入内容脚本的问题与解决

解决Chrome扩展Manifest V3点击图标注入代码的问题

你的代码核心问题

  1. API版本不兼容:Manifest V3已废弃chrome.tabs.executeScript,需改用chrome.scripting.executeScript
  2. 权限缺失:使用脚本注入API需要在manifest中声明scripting权限
  3. 重复注入风险:你同时配置了自动注入所有页面的content_scripts和点击触发的注入,会导致代码重复执行

修正后的完整配置

manifest.json

移除自动注入的content_scripts,添加scripting权限:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "description": "Description of my extension",
  "permissions": ["activeTab", "scripting"],
  "background": {
    "service_worker": "background.js"
  }
}

background.js

改用新的脚本注入API,处理异步逻辑并添加加载状态:

chrome.action.onClicked.addListener(async (tab) => {
  // 临时设置弹窗显示加载状态
  chrome.action.setPopup({ tabId: tab.id, popup: "loading.html" });

  try {
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ["content.js"]
    });
    // 加载完成后清空弹窗
    chrome.action.setPopup({ tabId: tab.id, popup: "" });
  } catch (err) {
    console.error("注入脚本失败:", err);
    chrome.action.setPopup({ tabId: tab.id, popup: "error.html" });
  }
});

content.js

全程用DOM API创建元素(避免innerHTML),添加样式隔离:

// 创建加载弹窗(模拟Loom的加载效果)
const loadingOverlay = document.createElement("div");
loadingOverlay.style.cssText = `
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999999;
`;
const loadingText = document.createElement("p");
loadingText.textContent = "加载中...";
loadingText.style.color = "#fff";
loadingOverlay.appendChild(loadingText);
document.body.appendChild(loadingOverlay);

// 模拟加载延迟,替换为实际业务逻辑
setTimeout(() => {
  // 移除加载弹窗
  loadingOverlay.remove();

  // 创建录制按钮
  const overlayButton = document.createElement("button");
  overlayButton.innerText = "Record";
  overlayButton.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 12px 24px;
    background: #2563eb;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    z-index: 999998;
    font-size: 16px;
  `;

  overlayButton.addEventListener("click", () => {
    // 这里编写录制逻辑
    alert("开始录制");
  });

  document.body.appendChild(overlayButton);
}, 1000);

最佳实践

  • 按需注入:仅在用户触发操作时注入脚本,避免自动注入所有页面消耗性能
  • 样式隔离:给注入的DOM元素添加高优先级样式和唯一标识,防止与页面原有样式冲突
  • 错误处理:注入脚本时添加异常捕获,处理权限不足、页面限制等情况
  • 上下文隔离:content script与页面JS上下文相互独立,若需交互可使用chrome.scripting.executeScript的world: "MAIN"选项(需注意安全风险)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:43:12