Blame view

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