Perfection Kills

by kangax

Exploring Javascript by example

← back 446 words

Detecting global variable leaks

detect-global bookmarklet

I have recently stumbled upon a blog post by Remy Sharp on detecting global variable leaks. As you probably know, Javascript is notorious at making such leaks way too easy. The problem is mainly with undeclared assignments which result in global variable declarations when variables are not found in the scope chain.

    var x = 1; // <== accidentally changed "," to ";"
        y = 2; // <== `y` is now a global variable

To be more precise, undeclared assignment actually results in global property assignment, not global variable declaration. The difference between two is rather subtle: variable declaration creates non-deletable property of a global object, whereas explicit or implicit property assignment creates deletable one. Another peculiarity can be observed in IE, where global property assignment is disallowed if there's an element in a document with the same-named ID or NAME value. Global variable declaration, on the other hand, quietly overwrites existing property in cases like this.

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 welcome

comments powered by Disqus