Categories
JavaScript Answers

How to Get All User Defined Window Properties with JavaScript?

Spread the love

To get all user defined window properties with JavaScript, we can use the Object.getOwnPropertyNames method to get all the non-inherited property keys of the window object.

For instance, we write:

let globalProps = [];
const readGlobalProps = () => {
  globalProps = Object.getOwnPropertyNames(window);
}

const findNewEntries = () => {
  const currentPropList = Object.getOwnPropertyNames(window);
  return currentPropList.filter(propName => globalProps.indexOf(propName) === -1);

}

readGlobalProps()
window.foobar = 2;
console.log(findNewEntries())

We have the readGlobalProps function that calls Object.getOwnPropertyNames with window and assigned the returned array of string keys to globalProps.

Then we define the findNewEntries function that gets the array of window keys again after adding user-defined window properties and assigned the returned results to currentPropList.

Then we call currentPropsList.filter to filter out the items that are also in globalProps to exclude the built non-user-defined keys from the returned array.

Next, we call readGlobalProps first to get all the non-user-defined window keys.

Then we add the foobar user-defined property.

And then we call findNewEntries to return the user-defined window property keys.

Therefore, the console.log should log ["foobar"].

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.