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

Chrome扩展遇Extension context invalidated错误,需在何处添加指定判断语句?

问题解决思路

错误原因与判断语句的正确位置

出现Extension context invalidated错误,是因为扩展上下文已失效(比如页面刷新、扩展重载),此时再调用Chrome扩展API就会报错。你添加的判断语句没生效,是因为没放在可能触发错误的代码执行入口:

  • 要放在click事件回调的最开头,确保上下文失效时直接退出,不执行后续逻辑;
  • 要放在MutationObserver的回调函数最开头,因为回调会在DOM变化时触发,此时上下文可能已经失效。

修改后的代码

content.js

document.addEventListener("click", (event) => {
  // 先判断上下文是否有效
  if (chrome.runtime.id === undefined) return;
  
  if (event.target.innerText === "Reply") {
    // 避免重复创建MutationObserver,先检查是否已有实例
    if (window.replyObserver) {
      window.replyObserver.disconnect();
    }

    const observer = new MutationObserver((mutations) => {
      // 回调里也要先判断上下文
      if (chrome.runtime.id === undefined) {
        observer.disconnect();
        return;
      }
      
      // 不要用之前缓存的元素集合,每次DOM变化后重新查询
      document.querySelectorAll("*").forEach(element => {
        if (element.classList.contains("aO7")) {
          console.log("找到目标元素");
          // 这里添加插入文本的逻辑,比如:
          // element.textContent += "你要插入的内容";
        }
      });
    });

    observer.observe(document.body, {
      attributes: true,
      childList: true,
      subtree: true
    });

    // 把观察者实例挂载到window,方便后续清理
    window.replyObserver = observer;

    chrome.runtime.sendMessage({
      type: "click_event"
    });
  }
});

额外优化点

  • 每次点击Reply时,先销毁之前的MutationObserver,避免多个观察者重复监听DOM变化,造成性能浪费;
  • 不要在点击时缓存元素集合,DOM更新后旧集合无法找到新生成的元素,要在Mutation回调里实时查询;
  • 匹配按钮文本用===更严谨,避免类型转换问题;
  • 在Mutation回调里检测到上下文失效时,主动断开观察者,避免无效回调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:30:38