JavaScript Ninja - The State Of Window

Posted at

Here is a simple quick&&dirty way of checking the state of the global-scope (window/top/self/...),
but you may apply the logic to any object, or even run the main method recursively to provide a compare status, as deep as required..

I'm going for a clear-example stuff, comparing before and after of one direct-layer of *stuff* added/removed into window.

It is especially useful for reverse-engineering a long and complicated, possibly obfuscated code,
which is too complex to view, but - naturally - will be much simpler to just see the result/effect on the DOM.





Just start with some place to store the before state:

window._before = {};
for(a in window) if(window.hasOwnProperty(a) window._before[a] = window[a];

(copy&&paste it to the JavaScript console, but don't execute it yet, we have more to add..)

--- do some HTML editing ---
you may inject an external javascript file,
or simply edit the HTML of the page using Chrome's developer-tools panel (the "elements" tab is just fine),
for example you can add the following Google-code, used for creating a custom Google-search for your website (just double click "body" and edit it as HTML, adding the following code. Easy!)
<script>
(function() {
var cx = 'XXXXXXXXXXXXXXXXXXXXX:YYYYY_ZZZZZ';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>


next, you'll have to "capture" the after-state, done pretty much like the before one:
(notice the "ignore-part", it's so you'll have cleaner results..)
window._after = {}
for(a in window){
if(false === window.hasOwnProperty(a)) continue; /* stuff you can not enumerate */
if(-1 !== a in ["_before","_after","_diff","ignore_me_too!"]) continue; /*ignore those names*/
window._after[a] = window[a];
}

(copy&&paste it to the JavaScript console, but don't execute it yet, we have more to add..)


the difference is calculated, quite easily with the following code:
window._diff = {};
for(a in window._after){ /*exist now but not before ==>> added*/
if(false === window._after.hasOwnProperty(a)) continue; /* stuff you can not enumerate */
if(false === window._before.hasOwnProperty(a)) window._diff[a] = {"diff":"added","obj":window._after[a]};
}

for(a in window._before){ /* exist before but not now ==>> deleted*/
if(false === window._before.hasOwnProperty(a)) continue; /* stuff you can not enumerate */
if(false === window._after.hasOwnProperty(a)) window._diff[a] = {"diff":"deleted","obj":window._after[a]};
}


(copy&&paste it to the JavaScript console, but don't execute it yet, we have more to add..)

that's it, just print the diff-object and you're done.

console.log(
window._diff
);