info-iframe.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('inherits')
  4. , JSON3 = require('json3')
  5. , utils = require('./utils/event')
  6. , IframeTransport = require('./transport/iframe')
  7. , InfoReceiverIframe = require('./info-iframe-receiver')
  8. ;
  9. var debug = function() {};
  10. if (process.env.NODE_ENV !== 'production') {
  11. debug = require('debug')('sockjs-client:info-iframe');
  12. }
  13. function InfoIframe(baseUrl, url) {
  14. var self = this;
  15. EventEmitter.call(this);
  16. var go = function() {
  17. var ifr = self.ifr = new IframeTransport(InfoReceiverIframe.transportName, url, baseUrl);
  18. ifr.once('message', function(msg) {
  19. if (msg) {
  20. var d;
  21. try {
  22. d = JSON3.parse(msg);
  23. } catch (e) {
  24. debug('bad json', msg);
  25. self.emit('finish');
  26. self.close();
  27. return;
  28. }
  29. var info = d[0], rtt = d[1];
  30. self.emit('finish', info, rtt);
  31. }
  32. self.close();
  33. });
  34. ifr.once('close', function() {
  35. self.emit('finish');
  36. self.close();
  37. });
  38. };
  39. // TODO this seems the same as the 'needBody' from transports
  40. if (!global.document.body) {
  41. utils.attachEvent('load', go);
  42. } else {
  43. go();
  44. }
  45. }
  46. inherits(InfoIframe, EventEmitter);
  47. InfoIframe.enabled = function() {
  48. return IframeTransport.enabled();
  49. };
  50. InfoIframe.prototype.close = function() {
  51. if (this.ifr) {
  52. this.ifr.close();
  53. }
  54. this.removeAllListeners();
  55. this.ifr = null;
  56. };
  57. module.exports = InfoIframe;