Last active
February 29, 2024 09:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 it wasn't enumerating non-enumerable properties - try the updated version?
Thanks, now it works :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I try to search for
'log'
it should give meconsole.log
, but instead it returnsundefined
. But when I search for'href'
it findsdocument.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.