Embed assets (child) - Parent to child iframe

by dshilkret

HTML

<h3><a href="https://jsfiddle.net/MadLittleMods/1zdkks19/">See parent fiddle: https://jsfiddle.net/MadLittleMods/1zdkks19/</a></h3>

<p>p test</p>
<section>section test</section>

JavaScript

(function() {
	/* restore the console as logiforms silences it */
	delete window.console;


	var loadedAssets = {};

	// Create IE + others compatible event handler
	var listenToFrameMessages = window.attachEvent ? window.attachEvent.bind(window, 'onmessage') : window.addEventListener.bind(window, 'message');

	// Listen to messages from parent window
	listenToFrameMessages(function(e) {
		if(e.data.debug) {
			console.log('Frame received message: ', e.data);
		}

		if(e.data.type === 'embed-assets') {
			// Pump the payload into the document
			if(e.data.debug) {
				console.log('embed payloads', e.data.embedPayload);
			}
			var payloads = [].concat(e.data.embedPayload);
			payloads.forEach(function(payload) {
				// If not already loaded
				if(!loadedAssets[payload.id]) {
					if(payload.tagName) {
						var element = document.createElement(payload.tagName);
						if(payload.contents) {
							element.innerHTML = payload.contents;
						}

						[].concat(Object.keys(payload.attributes || {})).forEach(function(attributeName) {
							var attributeValue = payload.attributes[attributeName];
							element.setAttribute(attributeName, attributeValue);
						});
						
						document.body.appendChild(element);

						// Mark it down as loaded
						loadedAssets[payload.id] = true;

						// Send a confirmation back that the iframe listened
						var acknowledge = {
							type: 'acknowledge-embed-assets',
							id: payload.id
						};
						e.source.postMessage(acknowledge, '*');
					}
				}
			});
		}
	}, false);

	// Send off a message to the parent frame
	// so they know we are looking for assets
	var requestAssets = {
		type: 'requesting-embed-assets'
	};
	parent.postMessage(requestAssets, '*');


})();