Search code examples
javascriptdom-eventsglobal-variables

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.


Solution

  • 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);
                  }
            }
    }