Skip to content

Instantly share code, notes, and snippets.

@YSaxon
Created November 16, 2023 16:26
Show Gist options
  • Save YSaxon/bdd00ce836dee657518d1937047e4ec6 to your computer and use it in GitHub Desktop.
Save YSaxon/bdd00ce836dee657518d1937047e4ec6 to your computer and use it in GitHub Desktop.
JS Console script to find the Redux store and state
function isReduxStore(obj) {
return obj && typeof obj === 'object' &&
typeof obj.getState === 'function' &&
typeof obj.dispatch === 'function' &&
typeof obj.subscribe === 'function';
}
function isValidIdentifier(key) {
return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(key);
}
function findReduxStoreBFS(root) {
const visited = new WeakSet();
const queue = [{ obj: root, path: 'window' }];
while (queue.length > 0) {
const { obj, path } = queue.shift();
if (isReduxStore(obj)) {
console.log('Redux store 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 = isValidIdentifier(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('No Redux store found in the window object.');
return null;
}
// Usage:
const state = findReduxStoreBFS(window).getState();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment