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();
});
Community
  • 1
  • 1
Michael W
  • 690
  • 1
  • 9
  • 22
  • `Object.prototype.constructor === Object` – silly little me Apr 24 '13 at 01:01
  • Good point, I looked into Object.constructor as well, but every attempt broke all the JS execution in Phantom – Michael W Apr 24 '13 at 01: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. – silly little me Apr 24 '13 at 01:12
  • @sillylittleme so how would I catch all handlers? Why: I want to pick out specific functions to run static analysis on them. – Michael W Apr 24 '13 at 01:17

0 Answers0