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 ifr
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.
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
}
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.