2018-11-23 11:43:16 +03:00
|
|
|
/* globals window */
|
|
|
|
module.exports = function layer0(frame) {
|
|
|
|
var getuid = (function (i) {
|
|
|
|
return function () {
|
|
|
|
return i += 1;
|
|
|
|
};
|
|
|
|
})(1);
|
|
|
|
var origin = new URL(frame.getAttribute('src')).origin;
|
|
|
|
var handlers = {};
|
2019-04-18 12:03:44 +03:00
|
|
|
var listener = null;
|
2018-11-23 11:43:16 +03:00
|
|
|
|
|
|
|
window.addEventListener('message', function (event) {
|
|
|
|
if (event.origin !== origin) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (!event.data || !event.data.uid) {
|
2018-12-04 06:54:04 +03:00
|
|
|
if (event.data.event) {
|
2019-04-18 12:03:44 +03:00
|
|
|
return listener && listener(event.data);
|
2018-12-04 06:54:04 +03:00
|
|
|
}
|
2018-11-23 11:43:16 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
var handler = handlers[event.data.uid];
|
|
|
|
if (!handler) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
delete handlers[event.data.uid];
|
|
|
|
handler(event.data.error, event.data.data);
|
|
|
|
});
|
|
|
|
|
|
|
|
function call(method, options, cb) {
|
|
|
|
var uid = getuid();
|
|
|
|
var data = {uid, method, options};
|
|
|
|
handlers[uid] = cb;
|
|
|
|
frame.contentWindow.postMessage(data, origin);
|
|
|
|
}
|
|
|
|
|
|
|
|
function listen(fn) {
|
2019-04-18 12:03:44 +03:00
|
|
|
if (listener) {
|
|
|
|
return false;
|
|
|
|
}
|
2018-11-23 11:43:16 +03:00
|
|
|
listener = fn;
|
2019-04-18 12:03:44 +03:00
|
|
|
return true;
|
2018-11-23 11:43:16 +03:00
|
|
|
}
|
|
|
|
|
2019-04-18 12:03:44 +03:00
|
|
|
return {
|
|
|
|
call: call,
|
|
|
|
listen: listen
|
|
|
|
};
|
2018-11-23 11:43:16 +03:00
|
|
|
};
|