There might be occasions where you want to inspect what is defined on the Window object, for instance is jQuery or Google Analytics loaded, or are there third party scripts that pollute your global Window scope?
In that case this script might come in handy. If you run it in your browsers console, it will create an object containing all user defined globals, nicely subdivided by type.
It works as follows: first, we declare 2 arrays, one empty called ‘filteredPropKeys’ and one that hold all the property names from the globals on Window called ‘allWindowPropKeys’. What we also need is an empty object that will hold all the user defined globals, let’s call it ‘customProperties’.
// create an iframe and append to body to load a clean window object
let filteredPropKeys,
allWindowPropKeys = Object.getOwnPropertyNames(win),
customProperties = {
array: {},
object: {}
},
iframe = doc.createElement("iframe");
// hide it just to be sure
iframe.style.display = "none";
// and append to the body
doc.body.append(iframe);
It then creates an iFrame element so we have a clean reference Window object. The iFrame is appended to body, so we can compare the original Window object with the iFrame Window object. Everything that is not defined on the iFrame window object will be added to the ‘filteredPropKeys’ array.
// filter the list against the properties that exist in the iframe
filteredPropKeys = allWindowPropKeys.filter(windowPropKeys => !iframe.contentWindow.hasOwnProperty(windowPropKeys));
When that is done, the cool part happens: We loop through the ‘filteredPropKeys’ array, check the type of the property against Window, and then add it to a corresponding property type on our customProperty object.
// now loop through the keys and make one big object containing all the custom properties
filteredPropKeys.forEach(key => {
const customPropKey = win[key];
const type = typeof customPropKey;
if (type === "object") {
// arrays are objects, too... so a special test is required
if (Array.isArray(customPropKey)) customProperties.array[key] = customPropKey;
else customProperties.object[key] = customPropKey;
} else {
// make a property for the remaining types
if (customProperties[`${type}`] === undefined) customProperties[`${type}`] = {};
customProperties[`${type}`][key] = customPropKey;
}
});
Finally, we log out the result with some added extra’s, the total number of Window globals, the total number of user defined globals, and the user defined globals themselves.
// write the result to the console.
con.log({
numWindowProps: allWindowPropKeys.length,
numCustomProps: filteredPropKeys.length,
customProperties
});
On this website, this will log out something like you see below. Pretty nice, right?
Finally, to keep things clean, we remove the iFrame we just created. And that’s all there is to it!
// clean up
iframe.remove();
Happy coding 😘