-
Notifications
You must be signed in to change notification settings - Fork 0
/
postmessage.js
56 lines (46 loc) · 1.37 KB
/
postmessage.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
56
define(['exports', 'module',
'events',
'class'],
function(exports, module, Emitter, clazz) {
function send(data, origin, win) {
if (!win) {
var frame;
for (var i = 0, len = window.frames.length; i < len; i++) {
frame = window.frames[i];
if (frame.location == origin) {
win = frame;
origin = frame.location.protocol + '//' + frame.location.host;
break;
}
}
}
if (!win) throw new Error('Unable to post message to "' + origin + '". No frame found.');
win.postMessage(data, origin);
}
function createListener(messageListener) {
var listener = new Listener();
if (messageListener) listener.on('message', messageListener);
return listener;
}
function Listener() {
Emitter.call(this);
}
clazz.inherits(Listener, Emitter);
Listener.prototype.listen = function() {
if (this._fn) return;
var self = this;
this._fn = function(e) {
self.emit('message', e.data, e.origin, e.source);
}
window.addEventListener('message', this._fn);
}
Listener.prototype.close = function() {
if (!this._fn) return;
window.removeEventListener('message', this._fn);
delete this._fn;
}
exports = module.exports = send;
exports.send = send;
exports.createListener = createListener;
exports.Listener = Listener;
});