-
Notifications
You must be signed in to change notification settings - Fork 51
/
js9PostMessage.js
81 lines (75 loc) · 2.01 KB
/
js9PostMessage.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
/*
*
* JS9 Post Message module (September 30, 2015)
*
* convenience routines to send a postMessage to JS9 inside an iFrame
*
* NB: This is an experimental module. Proceed with caution!
*
* Principals: Eric Mandel
* Organization: Center for Astrophysics | Harvard & Smithsonian, Cambridge MA
* Contact: [email protected]
*
* Copyright (c) 2015 - 2022 Smithsonian Astrophysical Observatory
*
*/
/*jslint plusplus: true, vars: true, white: true, continue: true, unparam: true, regexp: true, browser: true, devel: true, nomen: true */
// eslint-disable-next-line no-unused-vars
const JS9PM = (function(){
"use strict";
/* return module */
const JS9PM = {};
JS9PM.error = function(s){
alert(`JS9PM ERROR: ${s}`);
throw s;
};
// initialize post message processing (for iframes)
JS9PM.init = function (id, target){
const pm = {cb: []};
if( !id ){
JS9PM.error("missing postMessage id for JS9");
}
pm.id = window.document.getElementById(id).contentWindow;
if( !pm.id ){
JS9PM.error("invalid postMessage id for JS9");
}
pm.target = target || "*";
window.addEventListener("message", (ev) => {
let msg;
const data = ev.data;
if( typeof data === "string" ){
// json string passed (we hope)
try{ msg = JSON.parse(data); }
catch(e){ JS9PM.error(`can't parse msg: ${data}`, e); }
} else if( typeof data === "object" ){
// object was passed directly
msg = data;
} else {
JS9PM.error("invalid return msg from postMessage");
}
if( pm.cb[msg.cmd] && msg.res ){
pm.cb[msg.cmd](msg.res);
delete pm.cb[msg.cmd];
}
});
return pm;
};
// send a postMessage to a JS9PM iframe
JS9PM.send = function(pm, cmd, args, cb){
let obj;
if( !pm || !pm.id || !cmd ){
JS9PM.error("invalid postMessage send for JS9");
}
if( typeof args === "function" ){
cb = args;
args = null;
}
obj = {cmd: cmd, args: args};
if( cb ){
pm.cb[cmd] = cb;
}
pm.id.postMessage(obj, pm.target);
};
// return namespace
return JS9PM;
}());