How to search the browser window object looking which object or variable has the searched-for value?

Viewed 2464

If I know I have a value say 'JohnSmith' stored in some object in the global space of the browser and I hit some breakpoint, how do I know which object or variable has a value of 'JohnSmith'? I have hundreds of objects and I don't want to manually search for it in dev tools. I have used some scripts in the console or snippet which traverse the all the objects but they all have failed to search properly or give some error message.

I tried JS Runtime Inspector which looked promising but it doesn't work at all in my version 61 of Chrome. Its subtab doesn't show up like their video shows.

1 Answers

Here's a snippet I keep in devtools snippets panel:

{
  const checked = new Set();
  const dig = (value, o=window, path='') => {
    function check(v, name) {
      if ((typeof v == 'string' || typeof v == 'number')
      && String(v).toLowerCase().includes(value)) {
        console.log('%s in %s %o', v, path + name, o);
      } else if (v && typeof v == 'object' && v != window && !v.nodeName) {
        dig(value, v, path + name + '.');
      }
    }
    if (o && o.forEach) {
      for (let len = o.length, i; i < len; i++)
        check(o[i], `[${i}]`);
    } else if (typeof o == 'object') {
      for (const k of Object.getOwnPropertyNames(o)) {
        if (k.startsWith('webkit'))
          continue;
        try {
          const v = o[k];
          if (checked.has(v))
            continue;
          checked.add(v);
          check(v, k);
        }
        catch(e) {}
      }
    } else
      check(v);
  };

  console.group();
  dig('JohnSmith');
  console.groupEnd();
}

You can run devtools snippets by pressing Ctrl-Enter.

Related