Last active
October 7, 2016 10:00
-
-
Save edtoken/1185a2e23dea88afa8577aee23f10bc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var IframeSocket = function (options) { | |
options = options || {}; | |
options.target = options.target || ''; | |
var isReady = false; | |
var iframe = undefined; | |
var listenCallbacks = []; | |
var initCache = []; | |
var _ready = function () { | |
isReady = true; | |
initCache = initCache.reverse(); | |
while (initCache.length) { | |
var data = initCache.pop(); | |
_post(data); | |
} | |
}; | |
var _post = function (data) { | |
if (!isReady) { | |
initCache.push(data); | |
return; | |
} | |
console.log(iframe); | |
iframe.contentWindow.postMessage(data, options.where); | |
}; | |
var _createIframe = function () { | |
var iframeUrl = options.iframeUrl; | |
var node = document.getElementById('custom-IframeSocket'); | |
if (node) { | |
node.remove(); | |
} | |
var ifr = document.createElement('iframe'); | |
ifr.id = 'auth-iframe'; | |
ifr.setAttribute('style', 'background:#fff;border:1px solid #fff;width: 300px;height: 300px;position:fixed;z-index: 100000;display: block;top: 0;left: 0;'); | |
ifr.src = iframeUrl; | |
ifr.onload = function () { | |
iframe = ifr; | |
_ready(); | |
}; | |
setTimeout(function () { | |
document.body.appendChild(ifr); | |
}, 500); | |
}; | |
var _listener = function (event) { | |
if (event.origin !== options.where) { | |
return; | |
} | |
for (var i = listenCallbacks.length; i--;) { | |
listenCallbacks[i](event.data); | |
} | |
}; | |
if (window.addEventListener) { | |
window.addEventListener("message", _listener, false); | |
} else { | |
window.attachEvent("onmessage", _listener); | |
} | |
_createIframe(); | |
return { | |
post: function (data) { | |
_post(data); | |
}, | |
listen: function (callback) { | |
listenCallbacks.push(callback); | |
} | |
} | |
}; | |
var iframeSocket = new IframeSocket({ | |
where: 'http://ploptions.com', | |
who: 'http://platform.ploptions.com', | |
iframeUrl: 'http://ploptions.com/hiddenhash' | |
}); | |
iframeSocket.listen(function (data) { | |
console.log('where push message', data); | |
}); | |
iframeSocket.post('asdasdasd'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment