Home > Software engineering >  how can i remove the event listener of html in chrome extensions?
how can i remove the event listener of html in chrome extensions?

Time:01-16

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.

CodePudding user response:

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);
  •  Tags:  
  • Related