You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.5 KiB

4 years ago
  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;