Find which variable contains value using Chrome Devtools

I am trying to access some values ​​in a remote web application to create a Chrome extension.

To do this, I would like to find which JS variable stores the given value, and I was wondering if it was possible to do some kind of "global search" by the values ​​of all the variables in memory.

Is this possible with any tool? Inspector, profiler, etc ??

+6
source share
2 answers

You can iterate over all elements of the global scope, for example:

var test = 123, someVar = 812; for(key in window){ if(typeof window[key] === 'number' && window[key] == 123){ console.log(key, window[key]); } } 

Combine this with some recursion, and you could theoretically iterate over all the objects and their child objects available in the object:

 function searchObject(object, search){ for(key in object){ if(typeof object[key] === 'number' || typeof object[key] === 'string'){ if(object[key] === search){ console.log(key, window[key]); } }else if(typeof object[key] === 'object'){ searchObject(object[key], search); } } } 

This is just a quick and dirty example. It only checks strict equality (so the "string does not contain"), and it iterates through the arrays using for in , which is evil. But this should give you an idea of ​​how this works.

Do not skip window or document to this function. This will not work due to circular links.


However, you can also place a breakpoint in your code in chrome dev tools .
Then you can check the current value of your variables in the "Area Scope" area on the right.

+3
source

All credits for this answer go in the next tone . See His answer for more information on issues / improvements for this snippet.

Code

 function globalSearch(startObject, value) { var stack = [[startObject,'']]; var searched = []; var found = false; var isArray = function(test) { return Object.prototype.toString.call( test ) === '[object Array]'; } while(stack.length) { var fromStack = stack.pop(); var obj = fromStack[0]; var address = fromStack[1]; if( typeof obj == typeof value && obj == value) { var found = address; break; }else if(typeof obj == "object" && searched.indexOf(obj) == -1){ if ( isArray(obj) ) { var prefix = '['; var postfix = ']'; }else { var prefix = '.'; var postfix = ''; } for( i in obj ) { stack.push( [ obj[i], address + prefix + i + postfix ] ); } searched.push(obj); } } return found == '' ? true : found; } 
+3
source

Source: https://habr.com/ru/post/977869/


All Articles