Month: July 2017

iframe, localStorage, postMessage

iframe, localStorage, postMessage

I recently needed to pass some data from one domain to the other. Using a server-side language, like PHP, wasn’t an option. The site that needed the data was built using Angular and communicated with an API service. I thought about it for a day or two and considered doing it a few ways.

I decided to put an iframe on the source page and pass the data to the target page using JavaScript. Doing it this way only requires me to change a little bit of the code for the Angular site. Below is some sample code that hasn’t been tested.

Parent page


<iframe src="http://localstorage.fishknee.com" frameborder="0" id="iframe"></iframe>
<button id="send">send data!</button>
<script>
var send = document.getElementById('send');
send.onclick = function() {
	var win = document.getElementById('iframe').contentWindow;
	win.postMessage(JSON.stringify({key: 'levi'}), "*");
}
</script>

Recipient page


<script>
window.onmessage = function(event) {
    console.log('received a message!');
    if(event.origin !== 'http://example.com') {
        console.error('origin is bad');
        return;
    }
    console.log('origin is good!');

    var payload = JSON.parse(event.data);
    localstorage.setItem(payload.key, JSON.stringify(payload.data));
}
</script>

Feel free to email me with any questions you may have.