Reputation: 12036
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.
Upvotes: 86
Views: 116762
Reputation: 4170
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.
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.
Upvotes: 96
Reputation: 176
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 property names.
Step 3
Create a new JavaScript file (myVars.js
).
Add the following code:
var windowArray = [ /* paste in the window property names from above */ ];
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
pageVars
and if required, pageFunctions
to the watch list by clicking on the plus button.
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.
Upvotes: 0
Reputation: 2465
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.
Upvotes: 0
Reputation: 81
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
}
Upvotes: 1
Reputation: 643
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.Upvotes: 37
Reputation: 312
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);
Upvotes: 20
Reputation: 400
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.
Upvotes: 2
Reputation: 2019
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.
Upvotes: -1
Reputation: 7333
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.
Upvotes: 8
Reputation: 664164
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.
Upvotes: 8
Reputation: 89
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
Upvotes: 4