-3

How do I detect all children of 'window' that are defined by the user?

I want to detect window.test, but I don't want to get window.Math. Is there a way to list those Variables?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M.P.
  • 3
  • 1

1 Answers1

1

Your question is interesting but does not show any research effort. I suggest you to add a bit more information. It may be useful for further readers who face the same problem...


When you load a web page, you get a fresh new window object. So if you want to detect custom properties, it is a good idea to store the initial state of window at the top level of your code. It will allow you later to retrieve the new properties using Object.getOwnPropertyNames() or Object.keys().

Object.getOwnPropertyNames()

var customKeys,
    // We save the initial length of the array containing window properties
    nbProps = Object.getOwnPropertyNames(window).length;
 
    // Custom properties
    window.foo = 'Foo';
    window.bar = 'Bar';

    // We get the latest properties that were internally pushed to the array
    customKeys = Object.getOwnPropertyNames(window).slice(nbProps);
    
    console.log(customKeys);

Object.keys()

var customKeys,
    // We save the initial length of the array containing window properties
    nbProps = Object.keys(window).length;
 
    // Custom properties
    window.foo = 'Foo';
    window.bar = 'Bar';

    // We get the latest properties that were internally pushed to the array
    customKeys = Object.keys(window).slice(nbProps);
    
    console.log(customKeys);

Object.getOwnPropertyNames() vs Object.keys()

The difference between Object.getOwnPropertyNames() and Object.keys() is enumerability. Object.getOwnPropertyNames() takes into account all properties of an object, including non-enumerable ones, whereas Object.keys() only takes into account enumerable properties.

Look at the following code:

console.log('Object.getOwnPropertyNames(window)');
console.log(Object.getOwnPropertyNames(window).length + ' properties');
console.log('Math? ' + Object.getOwnPropertyNames(window).includes('Math'));

console.log('Object.keys(window)');
console.log(Object.keys(window).length + ' properties');
console.log('Math? ' + Object.keys(window).includes('Math'));
Badacadabra
  • 8,043
  • 7
  • 28
  • 49