JavaScript Library for Secure Cross Domain iFrame Communication
Porthole is a small Javascript library that makes it safe and easy to communicate with cross domain iFrames. Porthole relies on hidden iFrames (later referred to a as proxy) to exchange information. The caller sets a url fragment with the message to pass. The proxy by virtue of being served from the same origin as the callee, invokes a callback method with an event object that contains the message read from the url fragment. The message signaling mechanism is based on a resize event.
Learn more about Porthole.
Porthole is designed with these goals in mind:
Include the Javascript.
<script type="text/javascript" src="porthole.min.js"></script>
Create your content iFrame. This is where the guest content lives. Make sure to give it a name.
<iframe id="guestFrame" name="guestFrame" src="http://other-domain.com/">
</iframe>
Define an event handler if you want to receive messages.
function onMessage(messageEvent) {
/*
messageEvent.origin: Protocol and domain origin of the message
messageEvent.data: Message itself
messageEvent.source: Window proxy object, useful to post a response
*/
}
Create a window proxy object on the main page.
var windowProxy;
window.onload=function(){
// Create a proxy window to send to and receive
// messages from the iFrame
windowProxy = new Porthole.WindowProxy(
'http://other-domain.com/proxy.html', 'guestFrame');
// Register an event handler to receive messages;
windowProxy.addEventListener(onMessage);
};
Create a window proxy object in the iFrame.
var windowProxy;
window.onload=function(){
// Create a proxy window to send to and receive
// messages from the parent
windowProxy = new Porthole.WindowProxy(
'http://parent-domain.com/proxy.html');
// Register an event handler to receive messages;
windowProxy.addEventListener(function(event) {
// handle event
});
};
Host a proxy.html file on each domain. The proxy simply starts the dispatcher.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Replace the url with your own location -->
<script type="text/javascript" src="https://raw.github.com/ternarylabs/porthole/master/src/porthole.min.js"></script>
<script type="text/javascript">
window.onload=function(){ Porthole.WindowProxyDispatcher.start(); };
</script>
</head>
<body>
</body>
</html>
Send a message.
windowProxy.post({'action': 'supersizeme'});
Note that if you have multiple iFrames, you can create as many WindowProxy objects as needed.
See it in action at http://sandbox.ternarylabs.com/porthole/
Brought to you by Ternary Labs.