-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathopener.coffee
87 lines (70 loc) · 2.03 KB
/
opener.coffee
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
Base = require './base'
class OpenerRuntime extends Base
constructor: (definition) ->
super definition
@connecting = false
@connected = false
@buffer = []
getElement: -> null
isConnected: -> @connected
setParentElement: (parent) ->
return
connect: ->
# Let the UI know we're connecting
@connecting = true
@emit 'status',
online: false
label: 'connecting'
# Start listening for messages from the iframe
window.addEventListener 'message', @onMessage, false
@once 'capabilities', =>
# Runtime responded with a capabilities message. We're live!
@connecting = false
@connected = true
@emit 'status',
online: true
label: 'connected'
@emit 'connected'
@flush()
# Request capabilities from opener
@postMessage 'runtime', 'getruntime', {}
timeout = setTimeout =>
# Keep trying until runtime responds
@postMessage 'runtime', 'getruntime', {}
, 500
updateIframe: ->
return
disconnect: ->
@connected = false
# Stop listening to messages
window.removeEventListener 'message', @onMessage, false
@emit 'status',
online: false
label: 'disconnected'
@emit 'disconnected'
send: (protocol, command, payload) ->
if @connecting
@buffer.push
protocol: protocol
command: command
payload: payload
return
@postMessage protocol, command, payload
postMessage: (protocol, command, payload) ->
return unless window.opener
msg = @_prepareMessage protocol, command, payload
window.opener.postMessage JSON.stringify(msg), '*'
onMessage: (message) =>
if message.source and message.source isnt @iframe.contentWindow
# Message from unrelated source
return
if typeof message.data is 'string'
data = JSON.parse message.data
else
data = message.data
@recvMessage data
flush: ->
for item in @buffer
@postMessage item.protocol, item.command, item.payload
@buffer = []
module.exports = OpenerRuntime