Detect Global Variables(edit)

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).

Globals

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 = {},
    exceptions, 
    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]
  }
}
iframe.style.display = 'none';
document.body.appendChild(iframe);
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]]
}
console.dir(differences);

And there it is :)

Comments

comments powered by Disqus