Let’s say I have a simple webpage with only a small js file:
document.addEventListener('click', (event) => {
console.log("click event fired");
});
document.addEventListener('keypress', (event) => {
console.log("keypress event fired");
});
How to use the firefox developer console to:
- Overwrite the addEventListener function so I can log which type it was listening to?
- After logging execute the original function code
Right now I have this:
Object.defineProperty(Document.prototype, "addEventListener", {
value: function () {
console.log("addEventListener of type ...? was fired");
// execute original function
}
});
Whenever the document is clicked, the output should be:
addEventListener of type click was fired
click event fired
Or when a key is pressed:
addEventListener of type keypress was fired
keypress event fired
edit: Using the debugger would not solve my problem. I would like to know which eventlisteners are present on a site, and automate this for a long list of sites.
2
Answers
You can simply use the
Document.prototype.addEventListener
to achieve your goal.example:
Your
value
is the new value of theaddEventListener()
function, not the callback function that’s provided which gets invoked. In order to log each time the event occurs, you need to modify the callback as well, which can be done by calling the originaladdEventListener()
function and then providing your own callback that performs the logging. Below I’m also updatingEventTarget.prototype
, which allows you to intercept theaddEventListener
on all elements that extend EventTarget:Note, by providing your own wrapper around the original callback function, using
removeEventListener()
won’t work as expected, to handle this (and another edge case where the same function reference is passed toaddEventListener()
), one idea to handle this it to keep a Map of the functions added as event handlers and reuse the custom callback when needed: