Detect Global Variables

I’ve got a handy little bookmarklet that I use to check whether any variables have slipped out in the to global namespace (i.e. on to the window object).


Note that all global variables (including functions) that have been added by your page, will be written to via console.log.

The bookmarklet will also prompt to filter out globals, i.e. if you don’t care about functions, just filter it out.

It won’t work in IE because it writes to the console.log – but globals are globals – so it can just as easily be tested in Firefox.

How it works

It’s fairly simple really. The bookmarklet creates a hidden iframe and loops through all the attributes on the window object removing the common ones.

Then there’s a small tweak to remove a few manually (addEventListener, document, location, navigator and window), partly because it’s an iframe, partly because I set the location to about:blank.

Every thing that remains was put there by the particular page.

The code

The code is simply a compressed bookmarklet version of the following:

var differences = {},
    globals = {},
    ignoreList = (prompt('Ignore filter (comma sep)?', '') || '').split(','),
    i = ignoreList.length,
    iframe = document.createElement('iframe');
while (i--) {
  globals[ignoreList[i]] = 1
for (i in window) {
  differences[i] = {
    'type': typeof window[i],
    'val': window[i]
} = 'none';
iframe.src = 'about:blank';
iframe = iframe.contentWindow || iframe.contentDocument;
for (i in differences) {
  if (typeof iframe[i] != 'undefined') delete differences[i];
  else if (globals[differences[i].type]) delete differences[i]
exceptions = 'addEventListener,document,location,navigator,window'.split(',');
i = exceptions.length;
while (--i) {
  delete differences[exceptions[i]]

And there it is :)

3 Responses to “Detect Global Variables”

  1. [...] Detect Global Variables – [...]

  2. [...] stumbled upon a blog post by Remy Sharp on detecting global variable leaks. He took that work and updated it a little to filter out [...]

  3. Hey, this sounds like a great idea. However, if I wanted to run it on Firefox without Firebug installed, any ideas? Instead of console.log, should I just alert? document.write? I’m going to play with it, but if you have already solved the problem, no reason for me to reinvent the (digital) wheel.

    I’m using Firefox 3.x, and I get “console not defined” when I click the [analyze] button. I’m just ass-u-me’ing that console is a Firebug object.

    If you fixed it somehow (e.g. a giant alert), then it would be compatible with IE, also.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight