Messager.js

Cross domain iframe communication

Download

Messager is a lightweight (1kb Gzipped) dependancy free wrapper for postMessage API. Messager allow you to send event to and from an iframe, cross domain or not.

Installation

Just include the minified version of Messager.js on your website :

<script src="messager/build/messager.min.js"></script>

Usage

Messager should be instanciated on both iframe and parent page.

On the host website :

var iframe = document.getElementById('myFrame');
var messager = new Messager({
    remoteWindow: iframe.contentWindow,
    local: "http://hostaddress.com/",
    remote: "http://iframeaddress.com/"
}); 

On the iframe's website :

var messager = new Messager({
    remoteWindow: window.parent,
    local: "http://iframeaddress.com/",
    remote: "http://hostaddress.com/"
}); 

Then, from the iframe or the host website, you can send event like this :

messager.send('eventName', {param: 'value'});

And listening to this event like that :

messager.on('eventName', callback);

The callback function will receveive the given parameters as argument.

Parameters

Here is the list of available parameters :

Name Default value Description
local null Hostname of the current website (iframe hostname or parent hostname). Required
remote null Hostname of the remote website (iframe hostname or parent hostname). Required
remoteWindow null Window object of the remote website. Required
window window Window object of the local website.

API

Here is the list of available APIs :

Name Description
send('eventName', parameters) Function to send event and parameters to the iframe / host.
on('eventName', callback) Callback to execute on the iframe or host to execute when receiving an event.

Example

On the host website, initialization of Messager :

var iframe = document.querySelector('iframe');
var messager = new Messager({
    local: 'https://projects.spope.fr',
    remote: 'https://anothersite.fr',
    remoteWindow: iframe.contentWindow
});

var button = document.querySelector('.demo_send');
button.addEventListener('click', function() {
    messager.send('toggle', {params: 'test'});
})

In the iframe, initialization of Messager :

var messager = new Messager({
    local: 'https://anothersite.fr',
    remote: 'https://projects.spope.fr',
    remoteWindow: window.parent
});

var callback = function(params) {
    document.querySelector('body').classList.toggle('active');
}

messager.bind('toggle', callback);