Fetching all (javascript) global variables in a page

Is there a way to retrieve the names/values of all global variables on a page?

I would like to write a javascript function to do the following:

  1. Find all global variables prefixed with 'xxx_' and stick them in an array (for e.g.)
  2. build a query string using the name value pairs as follows: xxx_glob_var1=value1&xxx_glob_var2=value2 etc

How do I do this?



Or you could simply run;


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


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;} );
// ["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..

In my case, the two top answers didn't work, thus I am adding another answer, to highlight the comment of Dan Dascalescu:


When I executed it, it gave:


where the player, positon, ability, obj_need_save, xx_saves are my actual global variables.

I just saw that there exists a similar answer to another question.


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"

You could do something like this:

for (var i in window) {
    // i is the variable name
    // window[i] is the value of the variable

Though with this, you'll get a bunch of extra DOM properties attached to window.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.