DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

4 3

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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

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! 👍

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay