3

There are a crap ton of global variables in a typical browser environment to begin with, and usually even more of them in whatever web app you might load. When I get side tracked from a session in devtools, I want to list all my own variables, to quickly see what I had uncovered already to resume, without trying to piece it together from the window and command line history, ideally without noise from the page, or browser object model.

(If you want all global variables, not just those you created in devtools, there's a Q&A for that here.)

Community
  • 1
  • 1
ecmanaut
  • 5,030
  • 2
  • 44
  • 66
  • Possible duplicate of [View list of all JavaScript variables in Google Chrome Console](http://stackoverflow.com/questions/2934787/view-list-of-all-javascript-variables-in-google-chrome-console) – Martin Zeitler Sep 01 '16 at 22:12

1 Answers1

3

Provided the page doesn't dynamically leak new identifiers into the global scope, this hack lists all the identifiers that have been created after the window identifier, which seems a pretty good match for this purpose. myids() just lists their names, whereas myvars() collects them into an object you can inspect, to see them all in context together:

function myids() {
  function notUs(i) { return i !== 'myids' && i !== 'myvars'; }
  var ids = Object.keys(window);
  return ids.slice(ids.indexOf('window') + 1).filter(notUs);
}

function myvars() {
  function gather(a, i) { a[i] = window[i]; return a; }
  return myids().reduce(gather, {});
}

It's not perfect, but better than nothing, and it should only have false positives, no false negatives.

ecmanaut
  • 5,030
  • 2
  • 44
  • 66
  • Interesting idea. It takes advantage of the fact that the `window` object has a `window` property (circular reference), which is the last enumerable property added in Chrome. The order of traversal is based on the order in which the properties are added to the object. This is browser specific, so although this works fairly well in Chrome, it gives you a lot of redundant properties in Safari and Firefox. Still pretty useful! – Gideon Pyzer Sep 01 '16 at 23:41
  • Yeah, it's enough to do the job in Chrome DevTools, where I spend most of my web dev time, and I figured that it's worth sharing, while maybe bringing attention to browser developers that the feature this hack implements turns out to be very useful. – ecmanaut Sep 03 '16 at 17:25