Is there a way in Javascript to get a list or dump the contents of all global variables declared by Javascript/jQuery script on a page? I am particularly interested in array
Here’s a simple, more modern snippet that logs an object with the globals and their values (rather than just the global variable names), which is usually what I’m looking for when debugging:
(function () {
const iframe = document.createElement('iframe')
iframe.setAttribute('hidden', '')
iframe.src = 'about:blank'
iframe.onload = function () {
// Iterate through the properties of the current `window` and reduce the output
// to only properties that are not in the iframe’s `window`.
console.debug(Object.entries(window).reduce((reducedObj, [property, value]) => {
// Check if the property does not exist in the iframe and if so, add it to
// the output object.
if (! (property in iframe.contentWindow))
reducedObj[property] = value
return reducedObj
}, {})))
// Clean up the iframe by removing it from the DOM.
iframe.remove()
}
// Append the iframe to the DOM to kick off loading.
document.body.append(iframe)
})()
Tip: You can also swap 'about:blank' with window.location to get only the globals set since the page was first loaded.
This uses an iframe to determine which properties to ignore like robocat’s answer, but it’s based on David Walsh’s solution.