C
C
ColdSpirit2020-03-16 17:01:29
JavaScript
ColdSpirit, 2020-03-16 17:01:29

Is it possible to track the change in the Eventlistener of an element? Or protect the EventListener from changes?

There is Firefox extension code that runs on the page as soon as it is created:

document.addEventListener("keydown", (e)=>console.log(e), false);

The problem is this: the page clears all listeners on elements after a while. I can't figure out how to get around this behavior without using timers.

Is there any way to protect the listener from deletion, maybe hide it somehow?
Or, as an alternative, how to track the moment when the listener is removed in order to re-embed it after some time?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
ColdSpirit, 2020-03-17
@ColdSpirit

In general, as I understand it, the listener was deleted like this :

var oldRoot = document.documentElement;
var newRoot = oldRoot.cloneNode(true);
oldRoot.parentNode.replaceChild(newRoot, oldRoot);

When cloning an object, listeners are not cloned. I had to track the event of the element using MutationObserver, and when deleting the old element with the listener, hang the listener on the new element:
var oldEventListenerKeeper = document.documentElement;

var observer = new MutationObserver(function(mutations)
{
  mutations.forEach(function(mutation)
  {
    mutation.removedNodes.forEach(function(removedElement)
    {
      if (removedElement == oldEventListenerKeeper)
      {
        var newEventListenerKeeper = document.documentElement;
        newEventListenerKeeper.addEventListener("keydown", (e)=>console.log(e), false);
        oldEventListenerKeeper = newEventListenerKeeper;
      }
    });
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question