10

i'm trying to remove Listeners. In console a code below is working. When i use code in Chrome extension i get: "Uncaught ReferenceError: getEventListeners is not defined". Why does this happen? Is there an equivalent to the function "getEventListeners"?

document.addEventListener('click', fireContentLoadedEvent, false);

function fireContentLoadedEvent () {
    console.log ("DOMContentLoaded");
    for (let i = 0; i < document.getElementsByClassName("someClass").length; i++) {
        plusButton = document.getElementsByClassName("someClass")[i]

        if ( getEventListeners(plusButton)["click"].length > 1) {

            plusButton.removeEventListener("click", getEventListeners(plusButton).click[1].listener);

        }
    }
}
TimeTq
  • 111
  • 1
  • 1
  • 3
  • Is `getEventListeners` part of extension? I know it is part of the command line interface, not part of JavaScript – epascarello Jul 22 '20 at 18:02
  • 6
    `getEventListeners` is only defined in console when devtools is opened. There's a convoluted equivalent via chrome.debugger API and DOMDebugger.getEventListeners command which you probably don't want as it displays a warning in all tabs. Assuming the listener is added by the page in its script, a practical solution is to run your content script with "run_at":"document_start" and hook EventTarget.prototype.addEventListener in [page context](/a/9517879) or add your own click handler that calls stopImmediatePropagation, also in page context. – wOxxOm Jul 22 '20 at 18:13
  • Does this answer your question? [Get event listeners attached to node using addEventListener](https://stackoverflow.com/questions/9046741/get-event-listeners-attached-to-node-using-addeventlistener) – evolutionxbox Jul 22 '20 at 18:50
  • @wOxxOm, could you tell more about chrome.debugger API and DOMDebugger.getEventListeners? – TimeTq Jul 23 '20 at 10:18
  • Look for demo extensions and examples of using chrome.debugger. See the [CDP documentation](https://chromedevtools.github.io/devtools-protocol/tot/) for more info on the command. – wOxxOm Jul 23 '20 at 10:21

1 Answers1

3

getEventListeners is part of the Console API and it's not available outside the browser console.

As mentioned in a comment, you can replicate it by spying on the addEventListener method before it is ever called, for example: https://stackoverflow.com/a/6434924/288906

In a browser extension you would also make sure to run this code in the main world (not the isolated one)

fregante
  • 29,050
  • 14
  • 119
  • 159