git ssb

0+

cel / pull-postmsg



Tree: 0e406483fa15d28f0f5eda0c569b37021fa66136

Files: 0e406483fa15d28f0f5eda0c569b37021fa66136 / index.js

1580 bytesRaw
1function fixJSON(key, value) {
2 if (value instanceof Error) return {
3 message: value.message,
4 stack: value.stack,
5 name: value.name,
6 code: value.code,
7 }
8 return value
9}
10
11function isOriginCompatible(a, b) {
12 return !a || a === '*' || a.slice(0, b.length) === b
13}
14
15module.exports = function (win, origin) {
16 var _cb, _msg
17
18 if(origin && origin[0] === '/') {
19 origin = location.origin + origin
20 }
21
22 function post(msg) {
23 if (!win) _msg = msg
24 else win.postMessage(JSON.stringify(msg, fixJSON), origin || '*')
25 }
26
27 function gotWin(_win) {
28 win = _win
29 if (_msg) {
30 var msg = _msg
31 _msg = null
32 post(msg)
33 }
34 }
35
36 return function (read) {
37 function onMessage(e) {
38 if(isOriginCompatible(origin, e.origin)) {
39 if(!win) gotWin(e.source)
40 if(!origin) origin = e.origin
41 var msg = JSON.parse(e.data)
42 switch (msg[0]) {
43 case 'read': return onRead(msg[1])
44 case 'next': return onNext(msg[1], msg[2])
45 }
46 }
47 }
48
49 function onRead(end) {
50 read(end, function (end, data) {
51 post(['next', end, data])
52 })
53 }
54
55 function onNext(end, data) {
56 if (end) window.removeEventListener('message', onMessage, false)
57 if (!_cb) return console.error('unexpected data', end, data)
58 var cb = _cb
59 _cb = null
60 return cb(end, data)
61 }
62
63 window.addEventListener('message', onMessage, false)
64
65 return function (end, cb) {
66 if(_cb) return cb(new Error('read too soon'))
67 _cb = cb
68 post(['read', end])
69 }
70 }
71}
72

Built with git-ssb-web