-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (80 loc) · 2.1 KB
/
index.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
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
var msgListeners = {}, triggered = {}, msg;
if(typeof window !== 'undefined') {
window.addEventListener('message', function _parsewindowmessage(event) {
try {
msg = JSON.parse(event.data);
} catch (e) {
event.preventDefault();
return;
}
if (msg.type) trigger(msg.type, msg, event.source, false);
}, false);
} else {
var window = "GLOBAL"; // Quite hacky. Think of a better way to work in environments without a `window` global variable
}
/**
* Listen for messages of a given type
*/
function listen(type, callback, internalonly) {
if (!msgListeners[type]) msgListeners[type] = [];
msgListeners[type].push({
callback: callback,
ext: !internalonly
});
}
function unlisten(type, callback) {
if (msgListeners[type]) for (var ii in msgListeners[type]) {
if (msgListeners[type][ii].callback == callback) return delete msgListeners[type][ii];
}
return false;
}
/*
* Calls callback if message has already happened (passing most recent value), then listens for future calls
*
* Only works for internal messages
*
*/
function listenExisting(type, callback) {
listen(type, callback, true);
if (triggered.hasOwnProperty(type)) {
callback(triggered[type], window);
}
}
/*
* Calls callback if message has already happened, otherwise listens for it once
*
* Only works for internal messages
*
*/
function waitFor(type, callback) {
function callbackwrapper(msg) {
unlisten(type, callbackwrapper, true);
callback(msg, window);
}
listenExisting(type, callbackwrapper, true);
}
function trigger(type, msg, source, internal) {
if (internal) triggered[type] = msg;
if (msgListeners[type]) for (var ii in msgListeners[type]) {
if (internal || msgListeners[type][ii].ext) {
try {
msgListeners[type][ii].callback(msg, source);
} catch (error) {
console.error(`Error when triggering pubsub message "${type}"\n`, error);
}
}
}
}
function send(type, msg, target) {
if (!target || target == window) return trigger(type, msg, window, true);
if (!msg) msg = {};
msg.type = type;
target.postMessage(JSON.stringify(msg), '*');
}
export {
send,
listen,
unlisten,
waitFor,
listenExisting,
}