Skip to content

Instantly share code, notes, and snippets.

@gabrieldance
Last active December 17, 2015 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieldance/5645495 to your computer and use it in GitHub Desktop.
Save gabrieldance/5645495 to your computer and use it in GitHub Desktop.
;(function() {
'use strict';
var giahost = 'http://gia.guim.co.uk';
var giaIframe = document.getElementById('gia-iframe');
if (giaIframe) {
if (giaIframe.dataset.src) {
giaIframe.src = [giaIframe.dataset.src, window.location.hash].join('');
}
}
window.addEventListener('hashchange', function() {
var message = {
hashchange: window.location.hash
};
// TODO It would be good to limit the postMessage to just Guardian domains
if (giaIframe) {
giaIframe.contentWindow.postMessage(message, '*');
} else {
window.parent.postMessage(message, '*');
}
});
window.addEventListener('message', function(e) {
if (giahost !== e.origin) {
// console.log('Reject message from ', e.origin);
return;
}
if (e.data.hashchange) {
window.location.hash = e.data.hashchange;
}
if (e.data.setIframeSize) {
var iframe = document.getElementById(e.data.setIframeSize.id) || giaIframe;
if (e.data.setIframeSize.height) {
iframe.style.height = e.data.setIframeSize.height + 'px';
}
if (e.data.setIframeSize.width) {
iframe.style.width = e.data.setIframeSize.width + 'px';
}
}
}, false);
})();
<!DOCTYPE html>
<html>
<head>
<title>Outer</title>
</head>
<body>
<h1>Outer</h1>
<p>
<a href="#1">#1</a>
<a href="#2">#2</a>
<a href="#3">#3</a>
<a href="#4">#4</a>
</p>
<iframe id="gia-iframe" data-src="http://gia.guim.co.uk/2013/03/iframe/inner.html" height="500">Sorry, your browser doesn't support iframes</iframe>
<p>This is a demo of using <a href="https://developer.mozilla.org/en-US/docs/DOM/window.postMessage">postMessage</a> to communicate between an iframe and the parent window, whilst avoiding <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS">CORS</a> restrictions, use a different host for the iframe to demonstrate.</p>
<p>The <a href="https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange">hashchange</a> event will be syncronised between both windows. Currently it is bound to a single iframe with the id <code>gia-iframe</code>.</p>
<p>The hash of the iframe will be set to the hash of the containing window if the attribute <code>data-src</code> is used instead of <code>src</code>.</p>
<script type="text/javascript" src="http://gia.guim.co.uk/2013/03/iframe/gia.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment