Reputation: 634
The scenario: I'm trying to figure out an existing HTML/JavaScript site with a convoluted API. It adds several properties to the window
object. I'd like to enumerate only those properties that are not builtins or defaults (e.g. exclude window.location
, window.parent
, etc.)
Is there an idiomatic JavaScript way to do this? I'd thought of doing a shallow copy in a blank HTML page, then "subtracting" those properties somehow when enumerating the real one.
Ideally, i'd want a way to dump objects to the console or in a watch as if none of the regular window
properties existed, only those added with JavaScript source.
Upvotes: 4
Views: 77
Reputation: 196002
Expanding on dystroy's answer, in the case where you cannot execute your code before the api, you can create a new window on the fly to grab its properties (since it will be 'clean')
(also using hasOwnProperty
to exclude inherited properties)
window.preexistingkeys = [];
var w = window.open();
for (var key in w) if(window.hasOwnProperty(key)) window.preexistingkeys.push(key);
w.close();
for (var key in window) {
if (window.hasOwnProperty(key) && window.preexistingkeys.indexOf(key)==-1) console.log(key, window[key]);
}
Upvotes: 2
Reputation: 382160
Here's a detailled version of what I proposed in comment :
window.preexistingkeys = [];
for (var key in window) window.preexistingkeys.push(key);
// your convoluted api here
for (var key in window) {
if (window.preexistingkeys.indexOf(key)==-1) console.log(key, window[key]);
}
Note that you may execute the first part at start of the page's header, before the import of external scripts. Here's a sample.
Upvotes: 5