socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

Array.prototype.indexOf on page kills socket.io client

Open crickeys opened this issue 14 years ago • 2 comments

I have a customer who uses our code which makes use of socket.io. I isolated a bug that would seem to just never set the event emitters of the socket.io-client so I would get Object # has no method 'on' when setting an event listener on the socket.

I isolated some javascript on their website and ran some tests. If I include this code after I load my sockets javascript file then it breaks. Without that code it's all good. I'm not sure if this would be classified as a bug in socket.io or simply a bad use of overriding the indexOf for Arrays. Or maybe I'm missing something else?

I can't just tell the client to take the code out because we have lots of clients and they can't/won't always control that. Is there a way to make socket.io more robust to avoid this issue? Any ideas?

Here is the offending code:

Array.prototype.indexOf = function (c, d) { for(var b = (d || 0); b < this.length; b++) { if(this[b] == c) { return b } } };

crickeys avatar Jan 06 '12 04:01 crickeys

I assume this is because one version of indexOf is using 2 arguments and the other uses 3. Is there a way to check the number of arguments that Array.prototype.indexOf has?

For example, I see in the generated socket.io-client code this is probably the conflicting line: if (Array.prototype.indexOf) return Array.prototype.indexOf.call(a, b, c);

Would there be a way of ammending that to ensure that not only is Array.prototype.indexOf defined but it also take 3 paramaters?

crickeys avatar Jan 06 '12 04:01 crickeys

This might work. Haven't tested it.

Array.prototype.indexOf = (function(original) {
  return function(c, d) {
    if (arguments.length > 2) return original(arguments);
    else {
      for (var b = (d || 0); b < this.length; b++) {
        if (this[b] == c) return b;
      }
    }
  };
})(Array.prototype.indexOf);

Southern avatar Jan 07 '12 23:01 Southern