How to list only properties / methods of JavaScript objects added at runtime?

Scenario: I'm trying to figure out an existing HTML / JavaScript site with a confusing API. It adds several properties to the window object. I would like to list only those properties that are not built-in or standard (e.g. exclude window.location , window.parent , etc.)

Is there an idiomatic JavaScript way to do this? I thought about making a shallow copy on an empty HTML page, and then β€œsubtracting” these properties in some way when listing the real one.

Ideally, I need a way to reset objects to the console or to the clock, as if none of the usual window properties existed, only those that were added with the JavaScript source code.

+4
source share
2 answers

Expanding dystroy's answer , in the case when you cannot execute your code before api, you can create a new window on the fly to capture 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]); } 
+2
source

Here is a detailed version of what I suggested in the 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]); }​ 

with violin

Note that you can complete the first part at the beginning of the page title before importing external scripts. Here is an example .

+5
source

Source: https://habr.com/ru/post/1436205/


All Articles