Fetching all (javascript) global variables in a page

In some cases you may want to find non-enumerable properties; therefore for..in won't work (spec, about chrome) and neither would Object.keys as both only use enumerable keys. Notice that for..in is different to in but we can't use this to iterate.

Here is a solution using Object.getOwnPropertyNames (compatibility is IE9+). I've also added support for when you do only want enumerable properties or if you want to search another in context (not global).

function findPrefixed(prefix, context, enumerableOnly) {
    var i = prefix.length;
    context = context || window;
    if (enumerableOnly) return Object.keys(context).filter( function (e) {return e.slice(0,i) === prefix;} );
    else return Object.getOwnPropertyNames(context).filter( function (e) {return e.slice(0,i) === prefix;} );
}
findPrefixed('webkit');
// ["webkitAudioContext", "webkitRTCPeerConnection", "webkitMediaStream", etc..

Then if you want to join e.g.

findPrefixed('webkit').map(function (e) {return e+'='+window[e];}).join('&');
// "webkitAudioContext=function AudioContext() { [native code] }&webkitRTCPeerConnection=function RTCPeerConnection() etc..

Or you could simply run;

Object.keys(window);

It will show a few extra globals (~5), but far fewer than the for (var i in window) answer.

Object.keys is available in Chrome 5+, Firefox 4+, IE 9+, and Opera 12, ty @rink.attendant.6


Something like this:

function getGlobalProperties(prefix) {
  var keyValues = [], global = window; // window for browser environments
  for (var prop in global) {
    if (prop.indexOf(prefix) == 0) // check the prefix
      keyValues.push(prop + "=" + global[prop]);
  }
  return keyValues.join('&'); // build the string
}

A test usage:

var xxx_foo = "foo";
xxx_bar = "bar";
window.xxx_baz = "baz";

var test = getGlobalProperties('xxx_');
// test contains "xxx_baz=baz&xxx_bar=bar&xxx_foo=foo"

Tags:

Javascript