Embed assets (parent) - Parent to child iframe
by dshilkret
HTML
<p>
We are embedding assets in this child iframe (look at the console):
</p>
<p>
The child iframe does have some special javascript to receive these assets. <a href="https://jsfiddle.net/MadLittleMods/rdcvwu70/">See child fiddle</a>
</p>
<iframe src="https://fiddle.jshell.net/MadLittleMods/rdcvwu70/20/show/light/">
JavaScript
var generateRandomString = function() {
return Math.random().toString(36).slice(2)
};
// Listen to message from child window
// for any acknowledgment of assets
var listenToFrameMessages = window.attachEvent ? window.attachEvent.bind(window, 'onmessage') : window.addEventListener.bind(window, 'message');
listenToFrameMessages(function(e) {
if(e.data.type === 'requesting-embed-assets') {
console.log('Parent detected that child is requesting assets');
}
else if(e.data.type === 'acknowledge-embed-assets') {
console.log('Child frame acknowledged asset with id: ', e.data.id);
}
});
// Send out the assets to the child iframe
$('iframe').each(function() {
var $this = $(this);
var payload = {
debug: true,
type: 'embed-assets',
embedPayload: [
{
id: generateRandomString(),
tagName: 'script',
attributes: {},
contents: 'console.log(\'test\');'
},
{
id: generateRandomString(),
tagName: 'script',
attributes: {
type: 'text/javascript',
src: 'https://codepen.io/anon/pen/OVGryN.js'
}
},
{
id: generateRandomString(),
tagName: 'style',
attributes: {},
contents: 'p { color: #0f0; }'
},
{
id: generateRandomString(),
tagName: 'link',
attributes: {
type: 'text/css',
rel: 'stylesheet',
href: 'https://codepen.io/anon/pen/JdVxoY.css'
}
},
]
};
$this[0].contentWindow.window.postMessage(payload, '*');
});