Detecting global variable leaks
var x = 1; // <== accidentally changed "," to ";"
y = 2; // <== `y` is now a global variable
Remy solves the problem with a bookmarklet that creates a blank context (essentially a window in an empty iframe), then uses that clean context to get the difference with the main one. The list of found variables is dumped into a console.
It’s worth mentioning that JSLint already allows detecting undeclared assignments, but JSLint can hurt feelings so we won’t use it. Well, actually JSLint performs so many validations, that it’s not always possible to detect undeclared assignments in huge scripts of legacy applications (like the one I wanted to examine). Running a test such as in this bookmarklet can be “applied on” any script.
The bookmarklet worked like a charm, but as soon as I plugged it into one of our applications, I was greeted with dozens of Prototype and Scriptaculous -related methods. On top of those, there were few google analytics and Mozilla -specific ones. Unfortunately, the original code was obfuscated and almost unreadable so I reproduced it from the scratch, this time making it possible to toggle certain property sets on and off. These property sets are - Prototype, Scriptaculous, Mozilla, Google Analytics and Firebug ones. The code is structured in such way that it should be easy to augment it with additional sets.
In the end, I found few leaks in one of our applications and even one in firebug (now fixed).
As usual, the bookmarklet and its source are on github. Feel free to fork it.Edit [9/5/2009]
Clarified global variable declaration vs. global property assignment (thanks to Garrett Smith)
Did you like this? Donations are welcomecomments powered by Disqus