DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

How to inspect unique globals

As a 3rd party developer, I often need to leverage existing site functionality without access to our client's source code. It's usually the case that we need to figure out which code is publicly accessible to reuse or extend in our A/B testing platform or tag manager.

Here's a handy function I created to inspect what unique properties are available on the window. The approach is to create a new iframe (with about:blank as the src) and use its contentWindow object as the blank canvas to compare against the parent window object to determine what properties were added to the global scope.

/**
 * Logs an object w/ all the unique global variables on a page 
 * 
 * @return {undefined}
 */
(function inspectUniqueGlobals() {

  // Create object that will contain unique global variables
  const uniqueProperties = {};

  // Use an iframe to compare variables
  const iframe = document.createElement('iframe');

  // Attach blank source iframe to DOM
  iframe.src = 'about:blank';

  // On iframe load, process global properties
  iframe.onload = function() {

    // Get list of standard global objects from the iframe
    const defaultGlobals = Object.keys(iframe.contentWindow);

    // Loop through every window-level variable
    for (let item in window) {
      const prop = window[item];

      /* If the property is not found in the iframe's globals,
         then add it to the uniqueProperties object */
      if (defaultGlobals.indexOf(item) === -1 &&
          window.hasOwnProperty(item)) {
            uniqueProperties[item] = prop;
      }
    }

    // Inspect unique window properties
    console.log(uniqueProperties);
  };

  // Add to document
  document.body.appendChild(iframe);
})();
Enter fullscreen mode Exit fullscreen mode

We can test this out right on this page on dev.to if we enter this code in the console:

All of these properties are unique to the dev.to blog post page. Depending on what we're trying to achieve, we may get lucky and find a function that's already built and does exactly what we're looking for. As an example, on this page there's a global toggleMenu function.

If we run it, we'll see that the user menu opens up:

window.toggleMenu();
Enter fullscreen mode Exit fullscreen mode

You can learn a lot about a site with what their developers have set to the global scope. Sometimes you'll see some not-so-great things like potential vulnerabilities or even promo codes that were probably not meant to have been discovered by the average visitor. 🙊

Whatever your use case, I hope you found this handy and insightful :)


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (0)