javascriptbrowserpropertieswindow-object

Get all user defined window properties?


Is there a way to find out all user defined window properties and variables (global variables) in javascript?

I tried console.log(window) but the list is endless.


Solution

  • You would need to do the work for yourself. Read in all properties, on the first possible time you can. From that point on, you can compare the property list with your static one.

    var globalProps = [ ];
    
    function readGlobalProps() {
        globalProps = Object.getOwnPropertyNames( window );
    }
    
    function findNewEntries() {
        var currentPropList = Object.getOwnPropertyNames( window );
    
        return currentPropList.filter( findDuplicate );
    
        function findDuplicate( propName ) {
            return globalProps.indexOf( propName ) === -1;
        }
    }
    

    So now, we could go like

    // on init
    readGlobalProps();  // store current properties on global object
    

    and later

    window.foobar = 42;
    
    findNewEntries(); // returns an array of new properties, in this case ['foobar']
    

    Of course, the caveat here is, that you can only "freeze" the global property list at the time where your script is able to call it the earliest time.