Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching all (javascript) global variables in a page

Tags:

javascript

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?

like image 502
Stick it to THE MAN Avatar asked Feb 09 '10 00:02

Stick it to THE MAN


People also ask

How do I see all global variables?

Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters". Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables (global and then local to each function).

Is it bad to use global variables in JavaScript?

Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.

Why should we avoid global variables in JavaScript?

Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn't overwrite values of another variable.


2 Answers

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

like image 190
pleshy Avatar answered Oct 02 '22 17:10

pleshy


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" 
like image 35
Christian C. Salvadó Avatar answered Oct 02 '22 18:10

Christian C. Salvadó