Created
October 5, 2016 16:02
-
-
Save GrahamWalters/c5b6aa20330114c217f6961e024a9aa5 to your computer and use it in GitHub Desktop.
Track Event Listeners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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