Julian Jelfs’ Blog

Nasty issue “sort of with” jquery hotkeys plugin

Posted in Javascript, jQuery by julianjelfs on July 8, 2009

I encountered a quite nasty JavaScript issue today. The symptom was that a page that had been working quite happily was suddenly causing IE to crash. After a lot of head scratching I finally tracked it down to the hotkeys jQuery plug-in. I should say up front that there is arguably nothing wrong with the hotkeys plug-in. What the hotkeys plug-in does is to take a copy of jQuery’s own bind function and stores it in a variable called __bind__ on the jQuery object. It then override the bind function with its own in order to extend the functionality for certain event types. If you bind an event that it is not interested in, it delegates the call back to the original jQuery function by calling this.__bind__.

Nothing wrong with that, perfectly sensible and works fine. The problem arises if you accidentally include the script file for the hotkeys plug-in twice. This is not that unlikely if you are writing components that may depend on it and write them such that each component is responsible for its own script registration. This is what I am doing. Ordinarily, duplicate scripts would be filtered out but there was a bug in that code so I ended up with duplicate scripts.

In that case, the second time the script loads,  the following script:

jQuery.fn.__bind__ = jQuery.fn.bind;
It overwrites __bind__ with the already overridden bind function i.e. itself. This has disastrous consequences when the plug-in subsequently calls __bind__ because it enters into an infinite loop and crashes the browser.
Although this only arises if you misuse the hotkeys plug-in, it seems that it could protect itself from this possibility by simply checking to see whether jQuery.fn.__bind__ had already been set before setting it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: