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?
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?
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()
.
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);
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);
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'));