2

My goal is to dynamically trace all registrations of event handlers in JavaScript, including but not limited to the document and window object. A piece of code is supposed to run before the rest of the website executes (onLoad) and should report what functions register for events. I want to wrap addEventListener, onmouseclick, onmessage etc. but I don't want to do this for each object individually.

I was looking into modifying the behavior of Object.constructor to perform self-inspection in the constructor. The code should be pretty trivial and look roughly like this:

var toWrap = [ "addEventListener", "onclick", "..." ];

for ( var x in toWrap ) {
    if ( toWrap[x] in this ) {
        this[toWrap[x]] = wrap(toWrap[x], this[toWrap[x]]);
    }
}

... but what is the right place to plug the code?

A pure JavaScript solution would be preferred over jQuery etc., I am implementing in PhantomJS.

Update:

I came up with the following code after reading this. It seems to work fine - any objections?

Object = ( function ( ) {
    this.wrap = function(e) {
        // ....
    }   
    this.wrap();
});
4
  • Object.prototype.constructor === Object Commented Apr 24, 2013 at 1:01
  • Good point, I looked into Object.constructor as well, but every attempt broke all the JS execution in Phantom Commented Apr 24, 2013 at 1:07
  • Not that I'd recommend it, but if you want to overwrite native methods for handler assignment, you'd need to do it on the prototype of the elements, like Element.prototype. You won't have success with trying to modify constructors themselves. Also, there's no onclick method. It's a simple property. But I'd wonder why you want/need this in the first place. Commented Apr 24, 2013 at 1:12
  • @sillylittleme so how would I catch all handlers? Why: I want to pick out specific functions to run static analysis on them. Commented Apr 24, 2013 at 1:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.