73

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.

Brad Larson
  • 169,393
  • 45
  • 393
  • 567
Flash Thunder
  • 11,114
  • 7
  • 42
  • 84
  • @FelixKling sounds like he wants the ones _used_, not _created_ – Alnitak Jun 24 '13 at 13:10
  • 1
    @Alnitak: Oh... mmh. Then maybe something like a code coverage test would have to be performed with special consideration of global variables. – Felix Kling Jun 24 '13 at 13:12
  • 1
    Not a duplicate...; The code analize might be very dificult and not 100% sure. – Flash Thunder Jun 24 '13 at 13:25
  • @DanDascalescu That's not exactly an duplicate. Since the answer on how to get all global members, vs all global members that have been defined / modified by a page, is quite a bit different, since the latter involves some additional steps. – Moritz Roessler Feb 26 '14 at 10:50
  • @C5H8NNaO4: the OP mentioned "READ, not changed added". – Dan Dascalescu Feb 26 '14 at 10:57
  • I had to rollback changes that someone made, because he did change the point of question. Touched doesn't mean modified. It means used anywhere in the site. Use = read or write. – Flash Thunder Feb 26 '14 at 11:02
  • @FlashThunder That was my bad. Sorry for the hassle, thanks for rolling back the changes :) – Moritz Roessler Feb 26 '14 at 11:03
  • 1
    @DanDascalescu My apologies to you too, you were right. – Moritz Roessler Feb 26 '14 at 11:04
  • 1
    @FlashThunder You might want to take a look at [this Question](http://stackoverflow.com/questions/6985582/monitor-all-javascript-object-properties-magic-getters-and-setters?rq=1) – Moritz Roessler Feb 26 '14 at 11:08
  • @C5H8NNaO4 Thank you. That may be an idea, have to check it out. Probably will have some spare time during weekend. – Flash Thunder Feb 26 '14 at 11:10
  • An interactive way to 'search' would be opening the devtools (e.g. in chrome) typing `window` + Enter and then click the triangle to expand the object tree. – ccpizza Oct 05 '17 at 13:14
  • @MoritzRoessler what's not a duplicate? Can you leave the link? – Him Feb 13 '21 at 01:11
  • @MoritzRoessler I don't know, the comment was removed when I explained why it's not a duplicate. Was 7 years ago. – Flash Thunder Feb 14 '21 at 08:08

9 Answers9

91

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.

card100
  • 76
  • 1
  • 7
stackErr
  • 4,072
  • 3
  • 22
  • 47
  • 4
    This is not the answer to my question. This lists all global variables, and I want to list only one touched by the site. – Flash Thunder Jun 24 '13 at 13:16
  • 1
    @FlashThunder: yes, you get like 6 extra properties, which you can filter out: "top", "window", "location", "external", "chrome", "document" in Chrome. Try running `Object.keys( window );` in a console right here on this page. – Dan Dascalescu Feb 26 '14 at 08:42
  • 1
    @DanDascalescu but he wants the variables that are used/read, object.keys(window) will list unused/unread ones. – stackErr Feb 26 '14 at 18:11
  • this does not work; `ReferenceError: window is not defined` – user5359531 Mar 01 '22 at 20:03
25

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:

  1. Things that are null or undefined are usually not interesting to look at.
  2. Most scripts will define a bunch of event handlers (i.e. functions) but they are also usually not interesting to dump out.
  3. Properties on window that are set by the browser itself, are usually defined in a special way, and their property descriptors reflect that. Globals defined with the assignment operator (i.e. 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.
jd20
  • 513
  • 5
  • 10
18

What i did was. I found a page with as little JavaScript / Frameworks as possible, logged all their keys in array. Then iterated all the keys on the new page and logged only those which were not listed in the previous site. You can try it or use my code snippet

var ks = ["postMessage","blur","focus","close","frames","self","window","parent","opener","top","length","closed","location","document","origin","name","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","customElements","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onanimationend","onanimationiteration","onanimationstart","onsearch","ontransitionend","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","isSecureContext","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onresize","onscroll","onseeked","onseeking","onselect","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting","onwheel","onauxclick","ongotpointercapture","onlostpointercapture","onpointerdown","onpointermove","onpointerup","onpointercancel","onpointerover","onpointerout","onpointerenter","onpointerleave","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","captureEvents","releaseEvents","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","scroll","scrollTo","scrollBy","onappinstalled","onbeforeinstallprompt","crypto","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute","indexedDB","webkitStorageInfo","sessionStorage","localStorage","chrome","visualViewport","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","addEventListener", "removeEventListener", "openDatabase", "dispatchEvent"]
var newKs = []
for (key in window) {
    if(ks.indexOf(key) == -1 && key !== "ks" && key !=="newKs") {
        newKs.push(key);
    }
}
console.log(newKs);
Viktor Veselý
  • 243
  • 3
  • 9
7

You could try to use getters for that, which you create for all existing global variables. Run this before the page is started:

Object.keys(window) // or
Object.getOwnPropertyNames(window).concat(
  Object.getOwnPropertyNames(Object.getPrototypeOf(window))
) // or whatever
.forEach(function(name) {
    var d = Object.getOwnPropertyDescriptor(window, name),
        def = Object.defineProperty,
        log = console.log.bind(console);
    if (d && !d.configurable)
        return log("cannot detect accessing of "+name);
    def(window, name, {
        configurable: true,
        get: function() {
            log("window."+name+" was used by this page!");
            if (d) {
                def(window, name, d);
                return d.get ? d.get() : d.value;
            } else { // it was not an own property
                delete window[name];
                return window[name];
            }
        },
        set: function(x) {
            log("Ugh, they're overwriting window."+name+"! Something's gonna crash.");
        }
    });
});

Of course property descriptors etc. are not compatible with older browsers. And notice that there are some global variables / window properties that might not be programmatically listable (like on* handlers), if you need them you will have to explicitly list them in the array. See the related questions List all properties of window object? and Cross Browser Valid JavaScript Names for that.

Yet I guess running a code coverage tool that whinges about undeclared global variables, like @stackErro suggested, is more helpful.

Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
7

Since this question is the first in google when searching for a way how to list global javascript variables, I will add my own answer for that. Sometimes you need to list global variables to see if your code does not have a variable leaked outside the scope (defined without 'var'). For that, use this in the debug console:

(function ()
{
   var keys=Object.keys( window );
   for (var i in keys)
   {
      if (typeof window[keys[i]] != 'function')
      console.log(keys[i], window[keys[i]]);
   }
})();

It will list the standard global variables, like window, document, location, etc. Those are just few. So you can find your leaked vars in the list easily.

Tomas M
  • 5,991
  • 5
  • 25
  • 33
  • 1
    That is still not an answer to my question... I was asking about `reading event` not `writting event` ... I need to list all variables that were used by side... for example if site reads `windows.navigator.userAgent`. – Flash Thunder Sep 18 '15 at 16:40
3

copy and paste the following code into your javascript console

var keys = Object.getOwnPropertyNames( window ),
    value;

for( var i = 0; i < keys.length; ++i ) {
    value = window[ keys[ i ] ];
    console.log( value );
}

all credits to RightSaidFred (Javascript - dumping all global variables)

i hope that helped you

Community
  • 1
  • 1
UNX
  • 69
  • 1
2

Easy way to list your globals I use sometimes. First put this code as early as possible, before any of your scripts executed.

var WINDOW_PROPS = Object.keys(window);

Then at the moment when you need to discover your globals just do something like this:

var GLOBALS = Object.keys(window)
    // filter the props which your code did not declare
    .filter(prop => WINDOW_PROPS.indexOf(prop) < 0)
    // prettify output a bit :) It's up to you...
    .map(prop => `${typeof window[prop]} ${prop} ${window[prop]}`)
    // sort by types and names to find easier what you need
    .sort();

console.log(GLOBALS.join("\n"));

I've used some ES6 features here to shorten the code. It's still not good for production, but good enough for debug purposes and should work in modern browsers.

0

Take the list from Object.keys(window), remove the global variables the browser generates by default, you are left with only the global variables you declared on page. Note: functions you declared also count as global variables.

const listGlobal = ()=> { //for debugging purposes
    //put this function inside your html or javascript. Go to the html page.
    //In chrome console type listGlobal(); to see list of global vars

    //Array of global variables that exist in chrome browser by default
    var stdChromeVars = ["parent","opener","top","length","frames","closed","location","self","window","document","name","customElements","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","origin","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","visualViewport","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onsearch","isSecureContext","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onresize","onscroll","onseeked","onseeking","onselect","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel","onauxclick","ongotpointercapture","onlostpointercapture","onpointerdown","onpointermove","onpointerup","onpointercancel","onpointerover","onpointerout","onpointerenter","onpointerleave","onselectstart","onselectionchange","onanimationend","onanimationiteration","onanimationstart","ontransitionend","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","queueMicrotask","requestAnimationFrame","cancelAnimationFrame","captureEvents","releaseEvents","requestIdleCallback","cancelIdleCallback","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","scroll","scrollTo","scrollBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","close","focus","blur","postMessage","onappinstalled","onbeforeinstallprompt","crypto","indexedDB","webkitStorageInfo","sessionStorage","localStorage","chrome","applicationCache","onpointerrawupdate","trustedTypes","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","caches","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute"];


    //load the current list of global variables
    let thisdocVars = Object.keys(window);

    //remove from the current list any variables that's in the browser default list
    stdChromeVars.forEach(DelFunc);
        function DelFunc(item) {
            thisdocVars.forEach((e,i)=>{if(e==item){thisdocVars.splice(i, 1);}});
        }

    //separate variables into functions and variables
    let thisdocfunc = [];
    let thisdocvar = [];
    thisdocVars.forEach((e)=>{if(typeof window[e]=="function"){thisdocfunc.push(e);}else{thisdocvar.push(e);}});
    console.log("Global Functions:\n" + thisdocfunc);
    console.log("Global Variables:\n" + thisdocvar);
    //Ctrl+Shift+i to see console in chrome
}
Mike
  • 21
  • 2
-1

You can try using JetBrains PhpStorm that's what I do, you can get a trial of 30 days for free for any system. Then you check on JSLint or JSHint or both I cant remember and then all your unused variables are underlined, highlighted with different color (according to theme) and visible on the scrollbar and when you hover over them it says unused variable;

EDIT: I think community version is free now.

Jacek Pietal
  • 1,960
  • 1
  • 18
  • 27
  • The OP was asking about global variables accessible via the browser console, not directly by analyzing the source code, which is what WebStorm does. – Dan Dascalescu Feb 26 '14 at 08:30
  • I think you're right @DanDascalescu but I also think this is the only way to check which variables are used. so I'll not delete this answer. – Jacek Pietal Feb 28 '14 at 14:00
  • I actually think it's more useful than digging what has been added in the window page. Having a tool that tells you exactly what's never used, well, looks a little better to me. – Sergi Juanola Nov 11 '14 at 12:22