Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active February 29, 2024 09:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/1843c267fc633688059dfa5e3b07d0dd to your computer and use it in GitHub Desktop.
Save mindplay-dk/1843c267fc633688059dfa5e3b07d0dd to your computer and use it in GitHub Desktop.
Recursively search the global namespace (window) for a variable with a given name
function findVar(varName) {
let seen = new Map();
function search(obj, prefix = "") {
if (seen.has(obj)) {
return;
}
seen.set(obj, true);
const names = new Set(Object.getOwnPropertyNames(obj));
for (const name in obj) {
names.add(name);
}
for (const name of names.values()) {
if (name === varName) {
console.log(prefix + name);
}
if ((Object.hasOwn(obj, name)) && (typeof obj[name] === "object") && (obj[name] != null)) {
search(obj[name], prefix + name + ".");
}
}
}
search(window);
}
@Stehlampe2020
Copy link

Stehlampe2020 commented Feb 28, 2024

When I try to search for 'log' it should give me console.log, but instead it returns undefined. But when I search for 'href' it finds document.location.href, so the recursivity doesn't seem to be a problem…
I'm running this on Firefox 124.0b4, in case that makes a difference. Firefox has an update ready, so when I'm on .0b5 I'll test again and see if it works then.
[EDIT]: Nope, still doesn't work.

@mindplay-dk
Copy link
Author

@Stehlampe2020 it wasn't enumerating non-enumerable properties - try the updated version?

@Stehlampe2020
Copy link

Thanks, now it works :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment