DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

Another way to inspect global variables

As a follow up to my earlier post on how to inspect unique global vars, this is another method I use when I want to search for existing code on a site.

// First remove iframes to prevent cross-origin access errors
document.querySelectorAll('iframe').forEach(iframe => iframe.remove());

// Create cache array to save existing keys
let cache = [];

// Use JSON.stringify replacer fn to allowlist non-circular props
const globals = JSON.stringify(window, (key, value) => {

  if (typeof value === 'object' && value !== null) {

    // If circular reference found, discard key
    if (cache.indexOf(value) !== -1) return;

    // Store value in our collection
    cache.push(value);
  }

  return value;
});

// Collect garbage
cache = null; 

console.log(globals);
copy(globals); // Chrome's built-in method to add to clipboard
Enter fullscreen mode Exit fullscreen mode

This code allows us to construct a stringified JSON map of all of the window's properties and subproperties. If using Chrome's console, the built-in copy() method will copy the stringified object to your clipboard. From here, I usually paste the code into beautifier.io to make it easier to read:

From there, I'll copy that beautified code into a normal text editor so that I can "Cmd/Ctrl + F" for values easier. The advantage of this method over the iframe way mentioned in my previous article is that this gives you an "at a glance" view of all the window's properties and so you can skim the list without having to toggle each object open in the console (the downside is that the window object might be huge depending on the site/page). You can also search for substring matches if you have an idea of what you're looking for with your code editor's search feature.

Perusing the output on dev.to, I noticed something interesting. Apparently there's a window.currentUser object which includes my followed tags as a string and apparently JavaScript has a hotness_score of 9940541 ๐Ÿ”ฅ. It's over 9 million! (breaks power scouter) ๐Ÿ’ฅ


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

Top comments (2)

Collapse
 
dailydevtips1 profile image
Chris Bongers

I'm a bit blown away by the Chrome copy function, literally didn't know that one!
Amazing article again Bill!

Collapse
 
js_bits_bill profile image
JS Bits Bill

Omg, it's SO handy! ๐Ÿ‘