Get all user defined window properties in JavaScript

One of the more bemoaned aspects of using JavaScript is that the entire state of the program is added to a global scope. In browsers, this is accessed with as the window object. While other languages have tightly enforced rules about which subroutines can access what data, in JavaScript you can effective access any part of the program any where you want. This might be bad for the concept of encapsulation but it is not without its benefits. It makes it easy to access any code or data that was written by somebody else, even if there is no API or interface for it.

The window comes with many predefined functions and data. Everything your browser provides you, including the entire DOM API is on there. This makes it cumbersome to simply inspect the window object. Here is a function that will filter all of that out, leaving only user defined properties.

const getUserProperties = () => {
  let results; 
  let currentWindow;
  let iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  currentWindow = Object.getOwnPropertyNames(window);
  results = currentWindow.filter((prop) => !iframe.contentWindow.hasOwnProperty(prop));
  document.body.removeChild(iframe);  
  return results;
};

This returns an array of strings of the names of the user defined properties. Open up your browser's development console and give it a try on some of your most used websites. You'll be surprised how much you can learn out them.