Skip to content

Instantly share code, notes, and snippets.

@Vanlalhriata
Created September 2, 2015 13:44
Show Gist options
  • Save Vanlalhriata/2142ec9810b3f523457e to your computer and use it in GitHub Desktop.
Save Vanlalhriata/2142ec9810b3f523457e to your computer and use it in GitHub Desktop.
Send messages between a root HTML window and one level of nested iframes
// Send messeges between a root window and its iframes.
// This works for only one level of iframes - because that was what I needed
// NOTE: jQuery is required
'use strict';
(function(root){
function broadcast(message){
// inform top only. top will broadcast to everyone else
root.top.postMessage(message, "*");
}
function receive(handler){
$(root).on('message', function(e){
var message = e.originalEvent.data;
handler(message);
});
}
// if message received on top, broadcast to all iframes
if (root.top == root) {
$(root).on('message', function(e){
var message = e.originalEvent.data;
$('iframe').each(function(index, element){
element.contentWindow.postMessage(message, "*");
});
});
}
var Messenger = {
broadcast: broadcast,
receive: receive
};
root.Messenger = Messenger;
})(window);
/* Example usage:
*****************
// Somewhere in an iframe:
Messenger.broadcast({
key: "navigateTo",
pageName: "placeOrderPage"
});
// Meanwhile, in another iframe:
Messenger.receive(function(message){
if (message.key == "navigateTo")
Navigation.navigateTo(message.pageName);
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment