Sohan Zaman
Sohan Zaman

Reputation: 661

Debug all functions fired on a specific event

I'm trying to see all fired functions on window scroll/resize or any other window events. Is there any way to debug this on Chrome? Maybe with any plugin?

Note: I don't want to detect the target element of event. I want to list all callbacks that are added to fire up with an event.

For example, think I have some callbacks on load like this:

window.addEventListener( 'load' , callback_function_a );
window.addEventListener( 'load' , callback_function_b );
window.addEventListener( 'load' , callback_function_c );
window.addEventListener( 'load' , function() {
    // do something
});

Now I want to list all those callbacks which are bound with 'load' event on window. Maybe there could be a way to debug the information in array or object like:

{
    'callback_function_a',
    'callback_function_b',
    'callback_function_c',
    'anonymous function',
}

or something else maybe?

Upvotes: 2

Views: 609

Answers (1)

terales
terales

Reputation: 3200

You can use getEventListeners(object):

// Works in console only
function callback_function_a() {}
function callback_function_b() {}
function callback_function_c() {}

window.addEventListener( 'load' , callback_function_a );
window.addEventListener( 'load' , callback_function_b );
window.addEventListener( 'load' , callback_function_c );
window.addEventListener( 'load' , function() {});

const listenerNames = getEventListeners(window).load.map(getListenerName);

console.log(listenerNames);

function getListenerName(entry) {
  return entry.listener.name ? entry.listener.name : 'anonymous'
}

Here is an example:

Print all <code>load</code> event listeners

Upvotes: 1

Related Questions