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

如何停止Chrome扩展中chrome.scripting.executeScript的执行?

停止Chrome扩展中chrome.scripting.executeScript注入脚本的方法

Chrome扩展无法直接从外部终止已通过chrome.scripting.executeScript注入到页面的脚本,必须让脚本自身实现终止逻辑,结合Chrome消息通信机制触发停止操作。以下是具体实现思路和修改后的代码:


核心思路

  1. 管理脚本内的定时器ID:将脚本中所有setTimeout的ID存入数组,方便后续批量清除
  2. 添加消息监听:在注入的脚本中监听扩展发来的停止指令,收到指令时清除所有定时器
  3. 弹窗分逻辑处理:点击按钮时根据当前状态,选择注入脚本或发送停止消息,避免重复注入

修改后的script.js

function script(duration) {
  // 存储所有定时器ID,用于后续清除
  const timerIds = [];

  // 外层200ms延迟定时器
  const outerTimer = setTimeout(() => {
    const buttons = document.querySelectorAll('[aria-label^="Invite"]');
    chrome.storage.local.set({ timer: buttons.length });
    
    buttons.forEach((btn, idx) => {
      // 每个按钮的延迟操作定时器,存入数组
      const btnTimer = setTimeout(() => {
        const button = btn;
        button.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
        button.style.backgroundColor = 'red';
      }, duration * 1000 * (idx + 1));
      timerIds.push(btnTimer);
    });
  }, 200);
  timerIds.push(outerTimer);

  // 监听扩展发来的停止消息
  const stopListener = (message, sender, sendResponse) => {
    if (message.action === 'stopScript') {
      // 批量清除所有定时器
      timerIds.forEach(id => clearTimeout(id));
      // 移除监听,避免重复触发
      chrome.runtime.onMessage.removeListener(stopListener);
      sendResponse({ status: 'stopped' });
    }
  };
  chrome.runtime.onMessage.addListener(stopListener);
}

export default script;

修改后的弹窗组件代码

function Popup() {
  const [isActive, setActive] = useState(false);
  const [timer, setTimer] = useState(0);

  const buttonRef = useRef();

  const onClick = async () => {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    if (isActive) {
      // 当前脚本处于运行状态,发送停止指令
      chrome.tabs.sendMessage(activeTab.id, { action: 'stopScript' }, (response) => {
        if (response?.status === 'stopped') {
          setActive(false);
        }
      });
    } else {
      // 当前未运行脚本,执行注入操作
      await chrome.scripting.executeScript({
        target: { tabId: activeTab.id },
        args: [DURATION],
        func: script,
      });
      setActive(true);
    }
  };

  // 其他原有代码...
}

补充说明

  • 如果脚本中包含其他异步操作(如fetch请求),需要额外保存AbortController实例,在停止时调用abort()终止请求
  • 停止后移除消息监听是为了避免同一页面多次注入脚本时出现重复监听的问题

内容的提问来源于stack exchange,提问作者PRATAP-PANABAKA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:01:18