Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect creation of new global variables?

I want watch for the creation of new global variables in Javascript so that, anytime a global variable is created, an event is fired.

I've heard of the watch() function but that is only for watching for specific variable names. I want a catchall.

like image 444
Sridatta Thatipamala Avatar asked Feb 23 '11 07:02

Sridatta Thatipamala


2 Answers

If you already know which names pollute your global namespace (see Intercepting global variable definition in javascript), you can use this trick to figure out when does it actually happen:

window.__defineSetter__('someGlobalVar', function() {
    debugger;
});

Be sure to have your developer tools open when you run this. Obviously works only if your browser supports __defineSetter__ but that's true for modern browsers. Also, don't forget to remove your debug code after you've finished.

Found here.

like image 120
Dmitry Pashkevich Avatar answered Sep 28 '22 09:09

Dmitry Pashkevich


I don't know how to make this work "on demand" as soon as a var is created, but I can suggest a polling approach. In a browser window, all global become a member of the global "window" object. (Because technically, "window" is the "global object"). So you could do something like the following:

1) enumerate all the properties on a window

window.proplist = window.proplist || {};
for (propname in window) {

    if (propname !== "proplist") {
      window.proplist[propname] = true;
    }
}

2) Set a timer to periodically "poll" window for new properties

setInterval(onTimer, 1000);

3) Wake up on the timer callback and look for new props

function onTimer() {
        if (!window.proplist) {
            return;
        }

        for (propname in window) {

              if (!(window.proplist[propname])) {
                 window.proplist[propname] = true;
                 onGlobalVarCreated(propname);
              }
        }
}
like image 21
selbie Avatar answered Sep 28 '22 08:09

selbie