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:
How do I do this?
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).
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With