What is the way to list all global variables that have been used by the site? Can any browser javascript debugger do that? By used I mean READ, not changed/added. Detect iframe ones, would be nice too.
PLEASE NOTE: I need to get a list of global variables "touched" by site. Not all of them or added ones or edited ones, the ones that were used anywhere in the site scripts.
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).
Are global variables stored in specific object? The answer is yes; they are stored in something called, officially, the global object. This object is described in Section 15.1 of the official ECMAScript 5 Specification.
Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
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. On the usage of more global variables in our code, it may lead to a maintenance issue.
In Chrome, go to Dev tools and open the console. Then type in the following:
Object.keys( window );
This will give you an Array of all the global variables.
EDIT
After searching on Google a bit, I found a way. You will need firefox and the jslinter addon.
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).
Now run Object.keys(window);
in the console and compare the results from both to figure out which ones are used.
This one-liner will get you pretty close, and does not require installing anything additional, or running code before the page loads:
Object.keys(window).filter(x => typeof(window[x]) !== 'function' && Object.entries( Object.getOwnPropertyDescriptor(window, x)).filter(e => ['value', 'writable', 'enumerable', 'configurable'].includes(e[0]) && e[1] ).length === 4)
It filters Object.keys(window) based on three principles:
window.foo = 'bar'
) have a specific-looking property descriptor, and we can leverage that. Note, if the script defines properties using Object.defineProperty with a different descriptor, we'll miss them, but this is very rare in practice.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