82

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
  • 170,088
  • 45
  • 397
  • 571
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
  • @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
  • https://astexplorer.net/#/gist/cc536e5919815cdb7220a33eee0fda28/8c6c5293d7cf76030ebd69f0f9cc8e5c5fe5c522 this won't detect when someone gets a property through window tho, as in window.document – Rainb Jan 15 '23 at 09:10

11 Answers11

94

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,130
  • 3
  • 24
  • 48
  • 5
    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
  • 2
    @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
36

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
  • 633
  • 7
  • 11
20

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ý
  • 263
  • 3
  • 10
8

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
  • 630,263
  • 148
  • 957
  • 1,375
8

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
  • 6,919
  • 6
  • 27
  • 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
4

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
  • 79
  • 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
  • 31
  • 3
0

There are two ways of going through this, the dynamic way, or the static way, the dynamic way is setting getters to all global elements somehow, and get notified when they get accessed, the other way is to use static analysis, parse the JavaScript and see all variables that have been accessed. However static analysis won't work very well if the code is obfuscated. Anyhow, we can use a Babel visitor that tells us exactly which identifiers have been used in a file.

export default function (babel) {
  const { types: t } = babel;

  return {
    name: "ast-transform", // not required
    visitor: {
      Program(path) {
        let obj = { window: [], this: [] };
        path.traverse({
          MemberExpression(path) {
            if (t.isIdentifier(path.node.object)) {
              let key = path.node.object.name;
              if (key in obj) {
                obj[key].push(path.node.property.name);
              }
            }
          }
        });
        t.addComment(
          path.container,
          "leading",
          `This is what I found:
Identifiers defined in this scope: ${JSON.stringify(Object.keys(path.scope.bindings))};
Identifiers used that are global or in prelude scope: ${JSON.stringify(Object.keys(path.scope.globals))}
All variables used at all: ${JSON.stringify(Object.keys(path.scope.references))}
Window and this attributes used: ${JSON.stringify(obj)}
`
        );
      }
    }
  };
}

online demo here. I hope this is useful to you.

Rainb
  • 1,965
  • 11
  • 32
0

I was looking for the same thing and cobbled something together which may be of assistance to someone else out there.

This is a multi step process, however the result should get you what you need.

Step 1 Create a basic html file containing the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Return All Global Variables</title>
  </head>
  <body>
    <script>
    var obj = window;
    var arr = [];
    var arrLength = 0;
    do Object.getOwnPropertyNames(obj).forEach(function(name) {
           arr.push(name);
       });
    while(obj = Object.getPrototypeOf(obj));
    arrLength = arr.length;
    arr.sort();
    for (var i = 0; i < arrLength; i++) {
        document.write('"' + arr[i] +'"');
        if(i < arrLength -1){
         document.write(', ');
        }
    }
    </script>
  </body>
</html>

Step 2 Run the html file you just created in the browser you are developing in. You will see a result similar to what is shown below:

"AbortController", "AbortSignal", "AbsoluteOrientationSensor", "AbstractRange", "Accelerometer", "AggregateError", "AnalyserNode", "Animation", "AnimationEffect", "AnimationEvent", "AnimationPlaybackEvent", "AnimationTimeline", "Array", "ArrayBuffer", "Atomics", "Attr", "Audio", "AudioBuffer", "AudioBufferSourceNode", "AudioContext", "AudioData", "AudioDecoder", "AudioDestinationNode", "AudioEncoder", "AudioListener", "AudioNode", "AudioParam", "AudioParamMap", "AudioProcessingEvent", "AudioScheduledSourceNode", "AudioSinkInfo", "AudioWorklet", "AudioWorkletNode", "AuthenticatorAssertionResponse", "AuthenticatorAttestationResponse", "AuthenticatorResponse", "BackgroundFetchManager", "BackgroundFetchRecord", "BackgroundFetchRegistration", "BarProp", "BaseAudioContext", "BatteryManager", "BeforeInstallPromptEvent", "BeforeUnloadEvent", "BigInt", "BigInt64Array", "BigUint64Array", "BiquadFilterNode", "Blob", "BlobEvent", "Bluetooth", "BluetoothCharacteristicProperties", "BluetoothDevice", "BluetoothRemoteGATTCharacteristic", "BluetoothRemoteGATTDescriptor", "BluetoothRemoteGATTServer", "BluetoothRemoteGATTService", "BluetoothUUID", "Boolean", "BroadcastChannel", "BrowserCaptureMediaStreamTrack", "ByteLengthQueuingStrategy", "CDATASection", "CSS", "CSSAnimation", "CSSConditionRule", "CSSContainerRule", "CSSCounterStyleRule", "CSSFontFaceRule", "CSSFontPaletteValuesRule", "CSSGroupingRule", "CSSImageValue", "CSSImportRule", "CSSKeyframeRule", "CSSKeyframesRule", "CSSKeywordValue", "CSSLayerBlockRule", "CSSLayerStatementRule", "CSSMathClamp", "CSSMathInvert", "CSSMathMax", "CSSMathMin", "CSSMathNegate", "CSSMathProduct", "CSSMathSum", "CSSMathValue", "CSSMatrixComponent", "CSSMediaRule", "CSSNamespaceRule", "CSSNumericArray", "CSSNumericValue", "CSSPageRule", "CSSPerspective", "CSSPositionValue", "CSSPropertyRule", "CSSRotate", "CSSRule", "CSSRuleList", "CSSScale", "CSSSkew", "CSSSkewX", "CSSSkewY", "CSSStyleDeclaration", "CSSStyleRule", "CSSStyleSheet", "CSSStyleValue", "CSSSupportsRule", "CSSTransformComponent", "CSSTransformValue", "CSSTransition", "CSSTranslate", "CSSUnitValue", "CSSUnparsedValue", "CSSVariableReferenceValue", "Cache", "CacheStorage", "CanvasCaptureMediaStreamTrack", "CanvasGradient", "CanvasPattern", "CanvasRenderingContext2D", "CaptureController", "ChannelMergerNode", "ChannelSplitterNode", "CharacterData", "Clipboard", "ClipboardEvent", "ClipboardItem", "CloseEvent", "Comment", "CompositionEvent", "CompressionStream", "ConstantSourceNode", "ContentVisibilityAutoStateChangeEvent", "ConvolverNode", "CookieChangeEvent", "CookieStore", "CookieStoreManager", "CountQueuingStrategy", "Credential", "CredentialsContainer", "CropTarget", "Crypto", "CryptoKey", "CustomElementRegistry", "CustomEvent", "CustomStateSet", "DOMError", "DOMException", "DOMImplementation", "DOMMatrix", "DOMMatrixReadOnly", "DOMParser", "DOMPoint", "DOMPointReadOnly", "DOMQuad", "DOMRect", "DOMRectList", "DOMRectReadOnly", "DOMStringList", "DOMStringMap", "DOMTokenList", "DataTransfer", "DataTransferItem", "DataTransferItemList", "DataView", "Date", "DecompressionStream", "DelayNode", "DelegatedInkTrailPresenter", "DeviceMotionEvent", "DeviceMotionEventAcceleration", "DeviceMotionEventRotationRate", "DeviceOrientationEvent", "Document", "DocumentFragment", "DocumentTimeline", "DocumentType", "DragEvent", "DynamicsCompressorNode", "Element", "ElementInternals", "EncodedAudioChunk", "EncodedVideoChunk", "Error", "ErrorEvent", "EvalError", "Event", "EventCounts", "EventSource", "EventTarget", "External", "EyeDropper", "FeaturePolicy", "FederatedCredential", "File", "FileList", "FileReader", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemHandle", "FileSystemWritableFileStream", "FinalizationRegistry", "Float32Array", "Float64Array", "FocusEvent", "FontData", "FontFace", "FontFaceSetLoadEvent", "FormData", "FormDataEvent", "FragmentDirective", "Function", "GPU", "GPUAdapter", "GPUAdapterInfo", "GPUBindGroup", "GPUBindGroupLayout", "GPUBuffer", "GPUBufferUsage", "GPUCanvasContext", "GPUColorWrite", "GPUCommandBuffer", "GPUCommandEncoder", "GPUCompilationInfo", "GPUCompilationMessage", "GPUComputePassEncoder", "GPUComputePipeline", "GPUDevice", "GPUDeviceLostInfo", "GPUError", "GPUExternalTexture", "GPUInternalError", "GPUMapMode", "GPUOutOfMemoryError", "GPUPipelineError", "GPUPipelineLayout", "GPUQuerySet", "GPUQueue", "GPURenderBundle", "GPURenderBundleEncoder", "GPURenderPassEncoder", "GPURenderPipeline", "GPUSampler", "GPUShaderModule", "GPUShaderStage", "GPUSupportedFeatures", "GPUSupportedLimits", "GPUTexture", "GPUTextureUsage", "GPUTextureView", "GPUUncapturedErrorEvent", "GPUValidationError", "GainNode", "Gamepad", "GamepadButton", "GamepadEvent", "GamepadHapticActuator", "Geolocation", "GeolocationCoordinates", "GeolocationPosition", "GeolocationPositionError", "GravitySensor", "Gyroscope", "HID", "HIDConnectionEvent", "HIDDevice", "HIDInputReportEvent", "HTMLAllCollection", "HTMLAnchorElement", "HTMLAreaElement", "HTMLAudioElement", "HTMLBRElement", "HTMLBaseElement", "HTMLBodyElement", "HTMLButtonElement", "HTMLCanvasElement", "HTMLCollection", "HTMLDListElement", "HTMLDataElement", "HTMLDataListElement", "HTMLDetailsElement", "HTMLDialogElement", "HTMLDirectoryElement", "HTMLDivElement", "HTMLDocument", "HTMLElement", "HTMLEmbedElement", "HTMLFieldSetElement", "HTMLFontElement", "HTMLFormControlsCollection", "HTMLFormElement", "HTMLFrameElement", "HTMLFrameSetElement", "HTMLHRElement", "HTMLHeadElement", "HTMLHeadingElement", "HTMLHtmlElement", "HTMLIFrameElement", "HTMLImageElement", "HTMLInputElement", "HTMLLIElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLLinkElement", "HTMLMapElement", "HTMLMarqueeElement", "HTMLMediaElement", "HTMLMenuElement", "HTMLMetaElement", "HTMLMeterElement", "HTMLModElement", "HTMLOListElement", "HTMLObjectElement", "HTMLOptGroupElement", "HTMLOptionElement", "HTMLOptionsCollection", "HTMLOutputElement", "HTMLParagraphElement", "HTMLParamElement", "HTMLPictureElement", "HTMLPreElement", "HTMLProgressElement", "HTMLQuoteElement", "HTMLScriptElement", "HTMLSelectElement", "HTMLSlotElement", "HTMLSourceElement", "HTMLSpanElement", "HTMLStyleElement", "HTMLTableCaptionElement", "HTMLTableCellElement", "HTMLTableColElement", "HTMLTableElement", "HTMLTableRowElement", "HTMLTableSectionElement", "HTMLTemplateElement", "HTMLTextAreaElement", "HTMLTimeElement", "HTMLTitleElement", "HTMLTrackElement", "HTMLUListElement", "HTMLUnknownElement", "HTMLVideoElement", "HashChangeEvent", "Headers", "Highlight", "HighlightRegistry", "History", "IDBCursor", "IDBCursorWithValue", "IDBDatabase", "IDBFactory", "IDBIndex", "IDBKeyRange", "IDBObjectStore", "IDBOpenDBRequest", "IDBRequest", "IDBTransaction", "IDBVersionChangeEvent", "IIRFilterNode", "IdentityCredential", "IdleDeadline", "IdleDetector", "Image", "ImageBitmap", "ImageBitmapRenderingContext", "ImageCapture", "ImageData", "ImageDecoder", "ImageTrack", "ImageTrackList", "Infinity", "Ink", "InputDeviceCapabilities", "InputDeviceInfo", "InputEvent", "Int16Array", "Int32Array", "Int8Array", "IntersectionObserver", "IntersectionObserverEntry", "Intl", "JSON", "Keyboard", "KeyboardEvent", "KeyboardLayoutMap", "KeyframeEffect", "LargestContentfulPaint", "LaunchParams", "LaunchQueue", "LayoutShift", "LayoutShiftAttribution", "LinearAccelerationSensor", "Location", "Lock", "LockManager", "MIDIAccess", "MIDIConnectionEvent", "MIDIInput", "MIDIInputMap", "MIDIMessageEvent", "MIDIOutput", "MIDIOutputMap", "MIDIPort", "Map", "Math", "MathMLElement", "MediaCapabilities", "MediaDeviceInfo", "MediaDevices", "MediaElementAudioSourceNode", "MediaEncryptedEvent", "MediaError", "MediaKeyMessageEvent", "MediaKeySession", "MediaKeyStatusMap", "MediaKeySystemAccess", "MediaKeys", "MediaList", "MediaMetadata", "MediaQueryList", "MediaQueryListEvent", "MediaRecorder", "MediaSession", "MediaSource", "MediaSourceHandle", "MediaStream", "MediaStreamAudioDestinationNode", "MediaStreamAudioSourceNode", "MediaStreamEvent", "MediaStreamTrack", "MediaStreamTrackEvent", "MediaStreamTrackGenerator", "MediaStreamTrackProcessor", "MessageChannel", "MessageEvent", "MessagePort", "MimeType", "MimeTypeArray", "MouseEvent", "MutationEvent", "MutationObserver", "MutationRecord", "NaN", "NamedNodeMap", "NavigateEvent", "Navigation", "NavigationCurrentEntryChangeEvent", "NavigationDestination", "NavigationHistoryEntry", "NavigationPreloadManager", "NavigationTransition", "Navigator", "NavigatorManagedData", "NavigatorUAData", "NetworkInformation", "Node", "NodeFilter", "NodeIterator", "NodeList", "Notification", "Number", "OTPCredential", "Object", "OfflineAudioCompletionEvent", "OfflineAudioContext", "OffscreenCanvas", "OffscreenCanvasRenderingContext2D", "Option", "OrientationSensor", "OscillatorNode", "OverconstrainedError", "PERSISTENT", "PageTransitionEvent", "PannerNode", "PasswordCredential", "Path2D", "PaymentAddress", "PaymentManager", "PaymentMethodChangeEvent", "PaymentRequest", "PaymentRequestUpdateEvent", "PaymentResponse", "Performance", "PerformanceElementTiming", "PerformanceEntry", "PerformanceEventTiming", "PerformanceLongTaskTiming", "PerformanceMark", "PerformanceMeasure", "PerformanceNavigation", "PerformanceNavigationTiming", "PerformanceObserver", "PerformanceObserverEntryList", "PerformancePaintTiming", "PerformanceResourceTiming", "PerformanceServerTiming", "PerformanceTiming", "PeriodicSyncManager", "PeriodicWave", "PermissionStatus", "Permissions", "PictureInPictureEvent", "PictureInPictureWindow", "Plugin", "PluginArray", "PointerEvent", "PopStateEvent", "Presentation", "PresentationAvailability", "PresentationConnection", "PresentationConnectionAvailableEvent", "PresentationConnectionCloseEvent", "PresentationConnectionList", "PresentationReceiver", "PresentationRequest", "ProcessingInstruction", "Profiler", "ProgressEvent", "Promise", "PromiseRejectionEvent", "Proxy", "PublicKeyCredential", "PushManager", "PushSubscription", "PushSubscriptionOptions", "RTCCertificate", "RTCDTMFSender", "RTCDTMFToneChangeEvent", "RTCDataChannel", "RTCDataChannelEvent", "RTCDtlsTransport", "RTCEncodedAudioFrame", "RTCEncodedVideoFrame", "RTCError", "RTCErrorEvent", "RTCIceCandidate", "RTCIceTransport", "RTCPeerConnection", "RTCPeerConnectionIceErrorEvent", "RTCPeerConnectionIceEvent", "RTCRtpReceiver", "RTCRtpSender", "RTCRtpTransceiver", "RTCSctpTransport", "RTCSessionDescription", "RTCStatsReport", "RTCTrackEvent", "RadioNodeList", "Range", "RangeError", "ReadableByteStreamController", "ReadableStream", "ReadableStreamBYOBReader", "ReadableStreamBYOBRequest", "ReadableStreamDefaultController", "ReadableStreamDefaultReader", "ReferenceError", "Reflect", "RegExp", "RelativeOrientationSensor", "RemotePlayback", "ReportingObserver", "Request", "ResizeObserver", "ResizeObserverEntry", "ResizeObserverSize", "Response", "SVGAElement", "SVGAngle", "SVGAnimateElement", "SVGAnimateMotionElement", "SVGAnimateTransformElement", "SVGAnimatedAngle", "SVGAnimatedBoolean", "SVGAnimatedEnumeration", "SVGAnimatedInteger", "SVGAnimatedLength", "SVGAnimatedLengthList", "SVGAnimatedNumber", "SVGAnimatedNumberList", "SVGAnimatedPreserveAspectRatio", "SVGAnimatedRect", "SVGAnimatedString", "SVGAnimatedTransformList", "SVGAnimationElement", "SVGCircleElement", "SVGClipPathElement", "SVGComponentTransferFunctionElement", "SVGDefsElement", "SVGDescElement", "SVGElement", "SVGEllipseElement", "SVGFEBlendElement", "SVGFEColorMatrixElement", "SVGFEComponentTransferElement", "SVGFECompositeElement", "SVGFEConvolveMatrixElement", "SVGFEDiffuseLightingElement", "SVGFEDisplacementMapElement", "SVGFEDistantLightElement", "SVGFEDropShadowElement", "SVGFEFloodElement", "SVGFEFuncAElement", "SVGFEFuncBElement", "SVGFEFuncGElement", "SVGFEFuncRElement", "SVGFEGaussianBlurElement", "SVGFEImageElement", "SVGFEMergeElement", "SVGFEMergeNodeElement", "SVGFEMorphologyElement", "SVGFEOffsetElement", "SVGFEPointLightElement", "SVGFESpecularLightingElement", "SVGFESpotLightElement", "SVGFETileElement", "SVGFETurbulenceElement", "SVGFilterElement", "SVGForeignObjectElement", "SVGGElement", "SVGGeometryElement", "SVGGradientElement", "SVGGraphicsElement", "SVGImageElement", "SVGLength", "SVGLengthList", "SVGLineElement", "SVGLinearGradientElement", "SVGMPathElement", "SVGMarkerElement", "SVGMaskElement", "SVGMatrix", "SVGMetadataElement", "SVGNumber", "SVGNumberList", "SVGPathElement", "SVGPatternElement", "SVGPoint", "SVGPointList", "SVGPolygonElement", "SVGPolylineElement", "SVGPreserveAspectRatio", "SVGRadialGradientElement", "SVGRect", "SVGRectElement", "SVGSVGElement", "SVGScriptElement", "SVGSetElement", "SVGStopElement", "SVGStringList", "SVGStyleElement", "SVGSwitchElement", "SVGSymbolElement", "SVGTSpanElement", "SVGTextContentElement", "SVGTextElement", "SVGTextPathElement", "SVGTextPositioningElement", "SVGTitleElement", "SVGTransform", "SVGTransformList", "SVGUnitTypes", "SVGUseElement", "SVGViewElement", "Sanitizer", "Scheduler", "Scheduling", "Screen", "ScreenDetailed", "ScreenDetails", "ScreenOrientation", "ScriptProcessorNode", "SecurityPolicyViolationEvent", "Selection", "Sensor", "SensorErrorEvent", "Serial", "SerialPort", "ServiceWorker", "ServiceWorkerContainer", "ServiceWorkerRegistration", "Set", "ShadowRoot", "SharedWorker", "SourceBuffer", "SourceBufferList", "SpeechSynthesisErrorEvent", "SpeechSynthesisEvent", "SpeechSynthesisUtterance", "StaticRange", "StereoPannerNode", "Storage", "StorageEvent", "StorageManager", "String", "StylePropertyMap", "StylePropertyMapReadOnly", "StyleSheet", "StyleSheetList", "SubmitEvent", "SubtleCrypto", "Symbol", "SyncManager", "SyntaxError", "TEMPORARY", "TaskAttributionTiming", "TaskController", "TaskPriorityChangeEvent", "TaskSignal", "Text", "TextDecoder", "TextDecoderStream", "TextEncoder", "TextEncoderStream", "TextEvent", "TextMetrics", "TextTrack", "TextTrackCue", "TextTrackCueList", "TextTrackList", "TimeRanges", "ToggleEvent", "Touch", "TouchEvent", "TouchList", "TrackEvent", "TransformStream", "TransformStreamDefaultController", "TransitionEvent", "TreeWalker", "TrustedHTML", "TrustedScript", "TrustedScriptURL", "TrustedTypePolicy", "TrustedTypePolicyFactory", "TypeError", "UIEvent", "URIError", "URL", "URLPattern", "URLSearchParams", "USB", "USBAlternateInterface", "USBConfiguration", "USBConnectionEvent", "USBDevice", "USBEndpoint", "USBInTransferResult", "USBInterface", "USBIsochronousInTransferPacket", "USBIsochronousInTransferResult", "USBIsochronousOutTransferPacket", "USBIsochronousOutTransferResult", "USBOutTransferResult", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "UserActivation", "VTTCue", "ValidityState", "VideoColorSpace", "VideoDecoder", "VideoEncoder", "VideoFrame", "VideoPlaybackQuality", "ViewTransition", "VirtualKeyboard", "VirtualKeyboardGeometryChangeEvent", "VisualViewport", "WakeLock", "WakeLockSentinel", "WaveShaperNode", "WeakMap", "WeakRef", "WeakSet", "WebAssembly", "WebGL2RenderingContext", "WebGLActiveInfo", "WebGLBuffer", "WebGLContextEvent", "WebGLFramebuffer", "WebGLProgram", "WebGLQuery", "WebGLRenderbuffer", "WebGLRenderingContext", "WebGLSampler", "WebGLShader", "WebGLShaderPrecisionFormat", "WebGLSync", "WebGLTexture", "WebGLTransformFeedback", "WebGLUniformLocation", "WebGLVertexArrayObject", "WebKitCSSMatrix", "WebKitMutationObserver", "WebSocket", "WebTransport", "WebTransportBidirectionalStream", "WebTransportDatagramDuplexStream", "WebTransportError", "WheelEvent", "Window", "WindowControlsOverlay", "WindowControlsOverlayGeometryChangeEvent", "Worker", "Worklet", "WritableStream", "WritableStreamDefaultController", "WritableStreamDefaultWriter", "XMLDocument", "XMLHttpRequest", "XMLHttpRequestEventTarget", "XMLHttpRequestUpload", "XMLSerializer", "XPathEvaluator", "XPathExpression", "XPathResult", "XRAnchor", "XRAnchorSet", "XRBoundedReferenceSpace", "XRCPUDepthInformation", "XRCamera", "XRDOMOverlayState", "XRDepthInformation", "XRFrame", "XRHitTestResult", "XRHitTestSource", "XRInputSource", "XRInputSourceArray", "XRInputSourceEvent", "XRInputSourcesChangeEvent", "XRLayer", "XRLightEstimate", "XRLightProbe", "XRPose", "XRRay", "XRReferenceSpace", "XRReferenceSpaceEvent", "XRRenderState", "XRRigidTransform", "XRSession", "XRSessionEvent", "XRSpace", "XRSystem", "XRTransientInputHitTestResult", "XRTransientInputHitTestSource", "XRView", "XRViewerPose", "XRViewport", "XRWebGLBinding", "XRWebGLDepthInformation", "XRWebGLLayer", "XSLTProcessor", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__", "__proto__", "addEventListener", "alert", "arr", "arrLength", "atob", "blur", "btoa", "caches", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "chrome", "clearInterval", "clearTimeout", "clientInformation", "close", "closed", "confirm", "console", "constructor", "constructor", "constructor", "cookieStore", "createImageBitmap", "credentialless", "crossOriginIsolated", "crypto", "customElements", "decodeURI", "decodeURIComponent", "devicePixelRatio", "dispatchEvent", "document", "encodeURI", "encodeURIComponent", "escape", "eval", "event", "external", "fetch", "find", "focus", "frameElement", "frames", "getComputedStyle", "getScreenDetails", "getSelection", "globalThis", "hasOwnProperty", "history", "i", "indexedDB", "innerHeight", "innerWidth", "isFinite", "isNaN", "isPrototypeOf", "isSecureContext", "launchQueue", "length", "localStorage", "location", "locationbar", "matchMedia", "menubar", "moveBy", "moveTo", "name", "navigation", "navigator", "obj", "offscreenBuffering", "onabort", "onafterprint", "onanimationend", "onanimationiteration", "onanimationstart", "onappinstalled", "onauxclick", "onbeforeinput", "onbeforeinstallprompt", "onbeforematch", "onbeforeprint", "onbeforetoggle", "onbeforeunload", "onbeforexrselect", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontentvisibilityautostatechange", "oncontextlost", "oncontextmenu", "oncontextrestored", "oncuechange", "ondblclick", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "ongotpointercapture", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onlanguagechange", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onlostpointercapture", "onmessage", "onmessageerror", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onoffline", "ononline", "onpagehide", "onpageshow", "onpause", "onplay", "onplaying", "onpointercancel", "onpointerdown", "onpointerenter", "onpointerleave", "onpointermove", "onpointerout", "onpointerover", "onpointerrawupdate", "onpointerup", "onpopstate", "onprogress", "onratechange", "onrejectionhandled", "onreset", "onresize", "onscroll", "onscrollend", "onsearch", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onselectionchange", "onselectstart", "onslotchange", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "ontransitioncancel", "ontransitionend", "ontransitionrun", "ontransitionstart", "onunhandledrejection", "onunload", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "open", "openDatabase", "opener", "origin", "originAgentCluster", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt", "performance", "personalbar", "postMessage", "print", "prompt", "propertyIsEnumerable", "queryLocalFonts", "queueMicrotask", "releaseEvents", "removeEventListener", "reportError", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scheduler", "screen", "screenLeft", "screenTop", "screenX", "screenY", "scroll", "scrollBy", "scrollTo", "scrollX", "scrollY", "scrollbars", "self", "sessionStorage", "setInterval", "setTimeout", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "status", "statusbar", "stop", "structuredClone", "styleMedia", "toLocaleString", "toString", "toolbar", "top", "trustedTypes", "undefined", "unescape", "valueOf", "visualViewport", "webkitCancelAnimationFrame", "webkitMediaStream", "webkitRTCPeerConnection", "webkitRequestAnimationFrame", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL", "webkitSpeechGrammar", "webkitSpeechGrammarList", "webkitSpeechRecognition", "webkitSpeechRecognitionError", "webkitSpeechRecognitionEvent", "webkitURL", "window"

The above is an array of all the window propery names.

Step 3

Create a new JavaScript file (myVars.js). Add the following code:

var windowArray = [insert result from step 2 in here];

var obj = window;
var pageVars = {}; // Page Variables Object
var pageFunctions = []; // Page Functions Array 
$(document).ready(function() {
    var x = 0;
    do Object.getOwnPropertyNames(obj).forEach(function(name) {
        if(windowArray.indexOf(name) > -1){
            // if the current window object iteration name exists in the windowArray Array, if it does, ignore the result
        }else{
            if(typeof(window[name]) === "function"){ // check if the object type is a function
                if(name.startsWith("$")){ // avoid jquery items
                    // black hole this result
                }else{
                    pageFunctions.push(name); // add function name to pageFunctions array
                }
            }else{
                if(name.startsWith("jQuery") || name.startsWith("page")){ // filter out any additional non-function page variables which may exist
                    // black hole this result
                }else{
                    pageVars[name] = window[name]; // add variable to pageVars Object
                }
            }
        }
       });
    while(obj = Object.getPrototypeOf(obj));
});

Step 4 Add the js file to the bottom of any file you are working on:

<script src="./path/to/myVars.js"></script>

Step 5

  1. Open the developer tools in the browser you are working in.
  2. Reload the page you are working on.
  3. Add pageVars and if required, pageFunctions to the watch list by clicking on the plus button. enter image description here
  4. Press the watch refresh button to make sure all variables are up to date.

You now have a working variable set based on only the variables you have created in your code.

I hope someone finds this useful.

Disclaimer: This was only tested on chrome and very little debugging and edge case detection was performed.

Majickal
  • 176
  • 2
  • 16
-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,980
  • 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