【问题标题】:is there a way to stop executeScript in chrome extension?有没有办法在 chrome 扩展中停止 executeScript?
【发布时间】:2023-02-22 21:36:59
【问题描述】:

有没有办法停止chrome.scripting.executeScript

我有这个代码

  const onClick = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const activeTabId = tabs[0].id;
      chrome.scripting.executeScript({
        target: { tabId: activeTabId },
        args: [DURATION],
        func: script,
      });
    });
   // some code...
  }

我从 2 天开始就在整个网络上搜索,但我无法找到一种方法来停止用户交互中的这个脚本。

我发现的一种方法是在用户交互时传递状态,但它会再次触发脚本。请看下面的代码

    function Popup() {
      const [isActive, setActive] = useState(false);
      const [timer, setTimer] = useState(0);
      const [stop, setStop] = useState(false);
    
      const buttonRef = useRef();
    
      const onClick = () => {
        setStop((x) => !x); // change
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          const activeTabId = tabs[0].id;
          chrome.scripting.executeScript({
            target: { tabId: activeTabId },
            args: [DURATION, stop], // passing the state here
            func: script,
          });
        });
      ....

onClick 来自将状态 stopfalse 更改为 true 的弹出窗口。但问题是这个切换再次调用脚本,请参阅下面的onClick(开始/停止连接)按钮

当点击这个按钮停止时,我需要想办法停止执行脚本。 对此有任何提示或想法表示赞赏。

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    如您所述,重复调用 chrome.scripting.executeScript 将多次执行脚本。

    解决此问题的最佳方法是使用消息传递 - 您可以使用 chrome.tabs.sendMessage 向给定页面(包括您注入的页面)中的内容脚本发送消息。

    您的弹出窗口将类似于:

    function Popup() {
      const [isActive, setActive] = useState(false);
      const [timer, setTimer] = useState(0);
      const [stop, setStop] = useState(false);
    
      const buttonRef = useRef();
    
      const onClick = () => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          const activeTabId = tabs[0].id;
          chrome.tabs.sendMessage(activeTabId, "stop");
        });
      };
    }
    

    在您的内容脚本中:

    chrome.runtime.onMessage.addListener((message) => {
      if (message === "stop") {
        // Do whatever you need to do to stop the script.
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2023-04-09
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2013-12-25
      相关资源
      最近更新 更多