简体   繁体   中英

Find which variable holds a value using Chrome Devtools

I'm trying to access some values in a remote web application to build a Chrome extension.

For that, I'd like to find which JS variable holds a given value, and I was wondering if one can do some sort of "global search" on the values of all variables in memory.

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

All credit for this answer goes to tomwrong . See his answer for more details on the issues/improvements for this snippet.

The 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;
}

You could iterate over all items in the global scope like this:

var test = 123,
    someVar = 812;

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

Combine that with some recursion, and you could theoretically iterate over all objects and their children, available in a 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 for strict equality (So no "string contains" ), and it iterates over arrays with for in , which is evil. But it should give you an idea of how it works.

Don't pass window or document to this function, though. That won't work due to circular references.


However, you can also place a breakpoint in your code in the chrome dev tools .
You can then inspect the current value of your variables in the "Scope Variables" area on the right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM