forked from fgnass/sendevent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
55 lines (46 loc) · 1.53 KB
/
client.js
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
module.exports = function(url, handle) {
if (typeof url == 'function') {
handle = url
url = '/eventstream'
}
/**
* Iframe-fallback for browsers that don't support EventSource.
*/
function createIframe() {
var doc = document
// On IE use an ActiveXObject to prevent the "throbber of doom"
// see: http://stackoverflow.com/a/1066729
if (window.ActiveXObject) {
doc = new ActiveXObject("htmlfile")
doc.write('<html><body></body></html>')
// set a global variable to prevent the document from being garbage
// collected which would close the connection:
window.eventStreamDocument = doc
// Expose a global function that can be invoked from within the iframe:
doc.parentWindow.handleSentEvent = handle
appendIframe(doc, url)
}
else {
// Most likely an old Android device. The trick here is not to send
// the 4KB padding, but to immediately reload the iframe afer a message
// was received.
window.handleSentEvent = handle
setTimeout(function() { appendIframe(document, url+'?close') }, 1000)
}
}
function appendIframe(doc, url) {
var i = doc.createElement('iframe')
i.style.display = 'none'
i.src = url
doc.body.appendChild(i)
}
var init = function() {
var source = new EventSource(url)
source.onmessage = function(ev) {
handle(JSON.parse(ev.data))
}
}
if (!window.EventSource) init = createIframe
if (window.attachEvent) attachEvent('onload', init)
else addEventListener('load', init)
}