简体   繁体   中英

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

im creating an extension for chrome and i have a question. i want to know, how can i remove an event from an element? this is my event handler:

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

i want my extension to add a mousemove event to html tag. and i did that.

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

i want to do something that when user clicked on my extension icon, if the badge text is on, remove the event listener from the html ; but i dont know how to remove the event listener from html tag. i tried but i couldnt.

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

i tried removeEventListener but it didnt work. i defined my function in global scope and it didnt work and i got an error that your function is undefined. i even tried to store the function in chromes storage. and etc? but how can i remove the event listener from html tag when developing an extension for chrome. thanks for helping.

When the code injected by executeScript runs, it creates a new function each time, so the previous function can't be removed because its internal pointer is different now.

You can persist the function via window :

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

Then you can remove it later in another executeScript:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM