Blame view

node_modules/sockjs-client/lib/transport/receiver/htmlfile.js 2.15 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  'use strict';
  
  var inherits = require('inherits')
    , iframeUtils = require('../../utils/iframe')
    , urlUtils = require('../../utils/url')
    , EventEmitter = require('events').EventEmitter
    , random = require('../../utils/random')
    ;
  
  var debug = function() {};
  if (process.env.NODE_ENV !== 'production') {
    debug = require('debug')('sockjs-client:receiver:htmlfile');
  }
  
  function HtmlfileReceiver(url) {
    debug(url);
    EventEmitter.call(this);
    var self = this;
    iframeUtils.polluteGlobalNamespace();
  
    this.id = 'a' + random.string(6);
    url = urlUtils.addQuery(url, 'c=' + decodeURIComponent(iframeUtils.WPrefix + '.' + this.id));
  
    debug('using htmlfile', HtmlfileReceiver.htmlfileEnabled);
    var constructFunc = HtmlfileReceiver.htmlfileEnabled ?
        iframeUtils.createHtmlfile : iframeUtils.createIframe;
  
    global[iframeUtils.WPrefix][this.id] = {
      start: function() {
        debug('start');
        self.iframeObj.loaded();
      }
    , message: function(data) {
        debug('message', data);
        self.emit('message', data);
      }
    , stop: function() {
        debug('stop');
        self._cleanup();
        self._close('network');
      }
    };
    this.iframeObj = constructFunc(url, function() {
      debug('callback');
      self._cleanup();
      self._close('permanent');
    });
  }
  
  inherits(HtmlfileReceiver, EventEmitter);
  
  HtmlfileReceiver.prototype.abort = function() {
    debug('abort');
    this._cleanup();
    this._close('user');
  };
  
  HtmlfileReceiver.prototype._cleanup = function() {
    debug('_cleanup');
    if (this.iframeObj) {
      this.iframeObj.cleanup();
      this.iframeObj = null;
    }
    delete global[iframeUtils.WPrefix][this.id];
  };
  
  HtmlfileReceiver.prototype._close = function(reason) {
    debug('_close', reason);
    this.emit('close', null, reason);
    this.removeAllListeners();
  };
  
  HtmlfileReceiver.htmlfileEnabled = false;
  
  // obfuscate to avoid firewalls
  var axo = ['Active'].concat('Object').join('X');
  if (axo in global) {
    try {
      HtmlfileReceiver.htmlfileEnabled = !!new global[axo]('htmlfile');
    } catch (x) {
      // intentionally empty
    }
  }
  
  HtmlfileReceiver.enabled = HtmlfileReceiver.htmlfileEnabled || iframeUtils.iframeEnabled;
  
  module.exports = HtmlfileReceiver;