Is there any method similar to getEventListeners that can be used in chrome extensions or even pure JS?
Asked Answered
K

1

8

Basically I'm making an extension that provides analytics based on the elements of a page. As the total number of elements often reaches numbers >5,000 but the elements with click events tied to them (the only ones I care about) are usually <50 it would be of great benefit performance wise if I could narrow down focus to only those elements I am interested in. Chrome's devtools function getEventListeners() is exactly what I'm after except, naturally, it only works in the chrome console. To me it would seem logical that there must be a way to do this in a Chrome extension? Pure JS would obviously be preferable but as right now my scope is limited to a single Chrome extension, anything that works there would do the job.

Thanks!

Komsomol answered 16/2, 2018 at 14:16 Comment(4)
wrap the addEventListener() proto, or use a custom event adder, like jQuery's .on() that logsLeandroleaning
Am I wrong in saying that this would only intercept events i.e. once a user tries to run them? This would be useless for my particular use case as I need to know what elements have events attached immediately on page load.Komsomol
ahh, gotcha. in that case it's simpler: you just can't.Leandroleaning
Ah disappointing, thanks for the help though!Komsomol
E
2

Alright so basically you can remake the window.getEventListeners() function like so:

const { addEventListener: nativeAddEventListenerPrototype } = Document.prototype;
const activeListeners = new Set();

Document.prototype.addEventListener = function(...nativeArgumentsList) {
    activeListeners.add(nativeArgumentsList);

    void Reflect.apply(nativeAddEventListenerPrototype, this, nativeArgumentsList);
};

Just make sure to inject this code before the page loads otherwise it cannot perform correctly, then basically everytime the website makes an event listener it will be stored inside that set so you can then navigate to each listener and do as you will. Hope this helps!

Erudition answered 9/6, 2023 at 22:34 Comment(1)
This is code pass with no errors but not work for me. Very Interest for me.Pinprick

© 2022 - 2024 — McMap. All rights reserved.