Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all user defined window properties?

Is there a way to find out all user defined window properties and variables (global variables) in javascript?

I tried console.log(window) but the list is endless.

like image 648
GriffLab Avatar asked Jun 22 '13 00:06

GriffLab


2 Answers

You could also compare the window against a clean version of the window instead of trying to snapshot during runtime to compare against. I ran this in console but, you could turn it into a function.

// make sure it doesn't count my own properties (function () {     var results, currentWindow,     // create an iframe and append to body to load a clean window object     iframe = document.createElement('iframe');     iframe.style.display = 'none';     document.body.appendChild(iframe);     // get the current list of properties on window     currentWindow = Object.getOwnPropertyNames(window);     // filter the list against the properties that exist in the clean window     results = currentWindow.filter(function(prop) {         return !iframe.contentWindow.hasOwnProperty(prop);     });     // log an array of properties that are different     console.log(results);     document.body.removeChild(iframe); }()); 
like image 119
jungy Avatar answered Sep 21 '22 16:09

jungy


You would need to do the work for yourself. Read in all properties, on the first possible time you can. From that point on, you can compare the property list with your static one.

var globalProps = [ ];  function readGlobalProps() {     globalProps = Object.getOwnPropertyNames( window ); }  function findNewEntries() {     var currentPropList = Object.getOwnPropertyNames( window );      return currentPropList.filter( findDuplicate );      function findDuplicate( propName ) {         return globalProps.indexOf( propName ) === -1;     } } 

So now, we could go like

// on init readGlobalProps();  // store current properties on global object 

and later

window.foobar = 42;  findNewEntries(); // returns an array of new properties, in this case ['foobar'] 

Of course, the caveat here is, that you can only "freeze" the global property list at the time where your script is able to call it the earliest time.

like image 38
jAndy Avatar answered Sep 21 '22 16:09

jAndy