Skip to content

Instantly share code, notes, and snippets.

@YSaxon
Created November 16, 2023 19:16
Show Gist options
  • Save YSaxon/8e83a2664cb35925d8972fa4b25f2752 to your computer and use it in GitHub Desktop.
Save YSaxon/8e83a2664cb35925d8972fa4b25f2752 to your computer and use it in GitHub Desktop.
JS Console script to recursively find an object starting from the window object
// a more generalized version of https://gist.github.com/YSaxon/bdd00ce836dee657518d1937047e4ec6
function createCriteriaFunction(propertyNames) {
if (!Array.isArray(propertyNames)) {
propertyNames = [propertyNames];
}
return function(obj) {
if (!obj || typeof obj !== 'object') return false;
return propertyNames.every(propertyName =>
typeof obj[propertyName] !== 'undefined'
);
};
}
function findObjectBFS(root, criteria) {
const criteriaFn = typeof criteria === 'function' ? criteria
: createCriteriaFunction(criteria);
const visited = new WeakSet();
const rootPath = root === window ? 'window' : '[ROOT OBJECT]';
const queue = [{ obj: root, path: rootPath }];
while (queue.length > 0) {
const { obj, path } = queue.shift();
if (criteriaFn(obj)) {
console.log('Object found at:', path);
return obj;
}
if (typeof obj === 'object' && obj !== null && !visited.has(obj)) {
visited.add(obj);
for (const key of Object.keys(obj)) {
try {
const property = obj[key];
const formattedKey = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(key) ? `.${key}` : `["${key}"]`;
const newPath = `${path}${formattedKey}`;
if (typeof property === 'object' && property !== null) {
queue.push({ obj: property, path: newPath });
}
} catch (error) {
console.error(`Error accessing property '${key}':`, error);
}
}
}
}
console.log('Object not found.');
return null;
}
// Usage example to find Redux store and state:
const reduxStore = findObjectBFS(window, ['getState', 'dispatch', 'subscribe', 'replaceReducer']);
const reduxState = reduxStore.getState();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment