Skip to content

Instantly share code, notes, and snippets.

@GrahamWalters
Created October 5, 2016 16:02
Show Gist options
  • Save GrahamWalters/c5b6aa20330114c217f6961e024a9aa5 to your computer and use it in GitHub Desktop.
Save GrahamWalters/c5b6aa20330114c217f6961e024a9aa5 to your computer and use it in GitHub Desktop.
Track Event Listeners
(function(window, document) {
'use strict';
/* global getEventListeners */
window.listenerCount = 0;
var ael = Node.prototype.addEventListener;
Node.prototype.addEventListener = function() {
window.listenerCount++;
window.console.log('add', arguments);
ael.apply(this, arguments);
};
var rel = Node.prototype.removeEventListener;
Node.prototype.removeEventListener = function() {
window.listenerCount--;
window.console.log('remove', arguments);
rel.apply(this, arguments);
};
window.findEventListeners = function() {
var items = Array.prototype.slice.call(
document.querySelectorAll('*')
).map(function(element) {
var listeners = getEventListeners(element);
return {
element: element,
listeners: Object.keys(listeners).map(function(k) {
return {
event: k,
listeners: listeners[k]
};
})
};
}).filter(function(item) {
return item.listeners.length;
});
items.map(function(item) {
var el = item.element,
id = el.id,
className = el.className;
if (className instanceof SVGAnimatedString) {
className = className.baseVal;
}
var str = el.tagName.toLowerCase() +
(id ? '#' + id : '') +
(className ? '.' + className.replace(/\s+/g, '.') : '');
str += ' ' +
item.listeners.map(function(l) {
return l.event + ': ' + l.listeners.length;
}).join(', ');
return str;
}).join('\n');
return items;
};
})(this, document);
// number of event listeners
listenerCount;
// Find elements with event listeners attached
findEventListeners();
// Highlight elements with listeners attached
findEventListeners().map(function(item) { item.element.style.outline = '2px solid red'; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment