Interfame JS, postMessage javascript class for symmetric parent to iframe communication

A simple parent to iframe communication library..
Suppose you have a web page and children iframes with javascript code.
Suppose you want to directly call functions from the parent window to children iframes.
Suppose you want also to directly call functions from the children iframes to the parent window.
So you need a symmetric parent to iframe communication library.
This is why you are here.
interfame.js is a little javascript library, less than a kb without comments, to do this in a very reliable way without complications and in full security.
Enjoy it!

Installation notes:

  • create na interfame.js file and copy inside the code below
  • put it somewhere in your js libs web app folders
  • include it in both parent and child iframe html page with the script tag
  • read the comments in code about how to use it

download code: interframe.js

Javascript library for symmetric parent to iframe communication using postMessage

// INTERFRAME COMMUNICATION =================================================
// written by Dino Olivieri
// http://www.onyrix.com
// to directly call funciont from and to parent window and children iframes
//
// examples
//
// from child to parent:
//
// suppose you have in parent a function like:
// function test(param1, param2){..}
// you can call it from child iframe with:
// interFrame.callParentFunction(‘test’,[valofparam1, valofparam2]);
//
// from parent to child
//
// suppose you have a child iframe with id=”myId” a function like:
// function test(param1, param2){..}
// you can call it from parent code with:
// interFrame.callIframeFunction(‘myId’,’test’,[valofparam1, valofparam2]);

var interFrame = {
receiveMessage: function(event){
var data = event.data;
if(typeof(window[data.func]) == “function”){
window[data.func].apply(null, data.params);
}
},
callParentFunction: function(functionName, params){
window.parent.window.postMessage({‘func’:functionName,’params’:params}, ‘*’);
},
callIframeFunction: function(iframeId, functionName, params){
document.getElementById(iframeId).contentWindow.postMessage({‘func’:functionName,’params’:params},’*’);
}
};

if (window.addEventListener) {
window.addEventListener (“message”, interFrame.receiveMessage, false);
}
else {
if (window.attachEvent) {
window.attachEvent(“onmessage”,interFrame.receiveMessage, false);
}
}

Documentation about the postMessage API

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://msdn.microsoft.com/it-it/library/cc197015%28v=vs.85%29.aspx

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close