browser.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var _globalThis;
  2. if (typeof globalThis === 'object') {
  3. _globalThis = globalThis;
  4. } else {
  5. try {
  6. _globalThis = require('es5-ext/global');
  7. } catch (error) {
  8. } finally {
  9. if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; }
  10. if (!_globalThis) { throw new Error('Could not determine global this'); }
  11. }
  12. }
  13. var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket;
  14. var websocket_version = require('./version');
  15. /**
  16. * Expose a W3C WebSocket class with just one or two arguments.
  17. */
  18. function W3CWebSocket(uri, protocols) {
  19. var native_instance;
  20. if (protocols) {
  21. native_instance = new NativeWebSocket(uri, protocols);
  22. }
  23. else {
  24. native_instance = new NativeWebSocket(uri);
  25. }
  26. /**
  27. * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
  28. * class). Since it is an Object it will be returned as it is when creating an
  29. * instance of W3CWebSocket via 'new W3CWebSocket()'.
  30. *
  31. * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
  32. */
  33. return native_instance;
  34. }
  35. if (NativeWebSocket) {
  36. ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {
  37. Object.defineProperty(W3CWebSocket, prop, {
  38. get: function() { return NativeWebSocket[prop]; }
  39. });
  40. });
  41. }
  42. /**
  43. * Module exports.
  44. */
  45. module.exports = {
  46. 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,
  47. 'version' : websocket_version
  48. };