簡體   English   中英

如何在 Chrome 擴展中刪除 html 的事件監聽器?

[英]how can i remove the event listener of html in chrome extensions?

我正在為 chrome 創建一個擴展,我有一個問題。 我想知道,如何從元素中刪除事件? 這是我的事件處理程序:

const handler = function (e) {
  console.log("on");
};

我希望我的擴展程序將html mousemove 我做到了。

document.querySelector("html").removeEventListener("mousemove", handler);

我想做一些事情,當用戶單擊我的擴展圖標時,如果徽章文本打開,則從html中刪除事件偵聽器; 但我不知道如何從html標記中刪除事件偵聽器。 我試過了,但我做不到。

chrome.scripting.executeScript({
  target: { tabId: tabs[0].id },
  function: myFuntion,
  args: ["remove"],
});

我試過removeEventListener但它沒有用。 我在全局 scope 中定義了我的 function,但它沒有工作,我收到一個錯誤,提示您的 function 未定義。 我什至嘗試將 function 存儲在 chrome 存儲中。 等等? 但是在為 chrome 開發擴展程序時,如何從 html 標記中刪除事件偵聽器。 謝謝你的幫助。

當executeScript注入的代碼運行時,每次都會創建一個新的function,所以之前的function不能去掉,因為它的內部指針現在不一樣了。

您可以通過 window 持久化window

window.handler = window.handler || function (e) {
  console.log("on");
};

然后您可以稍后在另一個 executeScript 中將其刪除:

document.querySelector("html").removeEventListener("mousemove", window.handler);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM