By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – How to intercept an eventhandler in javascript?
JavaScript

Javascript – How to intercept an eventhandler in javascript?

Admin
Last updated: 2024/02/07 at 6:04 PM
Admin
Share
3 Min Read
How to intercept an eventhandler in javascript?

Problem:

Let’s say I have a simple webpage with only a small js file:

Contents
Problem:Solution:
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:

  1. Overwrite the addEventListener function so I can log which type it was listening to?
  2. 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.

Solution:

Your value is the new value of the addEventListener() 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 original addEventListener() function and then providing your own callback that performs the logging. Below I’m also updating EventTarget.prototype, which allows you to intercept the addEventListener on all elements that extend EventTarget:

const proto = EventTarget.prototype;
const _addEventListener = EventTarget.prototype.addEventListener;
Object.defineProperty(proto, "addEventListener", {
  value: function (type, fn, ...rest) {       
      _addEventListener.call(this, type, function(...args) {
        console.log(`addEventListener of type ${type} was fired`);
        return fn.apply(this, args);
      }, ...rest);
  }
});

document.addEventListener("keydown", () => {
  console.log("keydown");
});

btn.addEventListener("click", () => {
  console.log("clicked");
});
<button id="btn">Click me</button>

Expand snippet

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 to addEventListener()), one idea to handle this it to keep a Map of the functions added as event handlers and reuse the custom callback when needed:

const proto = EventTarget.prototype;
const _addEventListener = EventTarget.prototype.addEventListener;
const _removeEventListener = EventTarget.prototype.removeEventListener;
const callbacks = new WeakMap();
Object.defineProperty(proto, "addEventListener", {
  value: function(type, fn, ...rest) {
    const cb = callbacks.get(fn) ?? function(...args) {
      console.log(`addEventListener of type ${type} was fired`);
      return fn.apply(this, args);
    }
    callbacks.set(fn, cb);
    _addEventListener.call(this, type, cb, ...rest);
  }
});

Object.defineProperty(proto, "removeEventListener", {
  value: function(type, fn, ...rest) {
    const cb = callbacks.get(fn);
    _removeEventListener.call(this, type, cb, ...rest);
  }
});

document.addEventListener("keydown", () => {
  console.log("keydown");
});

const mouseover = () => console.log("hover");
para.addEventListener("mouseover", mouseover);

btn.addEventListener("click", () => {
  console.log("clicked, removing event listener");
  para.removeEventListener("mouseover", mouseover);
});
p {
  background: yellow;
}
<p id="para">Hover me</p>
<button id="btn">Remove hover event listener</button>

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Show/hide multiple images individually Javascript – Show/hide multiple images individually
Next Article How to get elements from an array that do not have certain letter, just using the for loop? Javascript – How to get elements from an array that do not have certain letter, just using the for loop?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?