iframed Analytics Events through GTM

For a freelance client I recently needed to register an Analytics event when a 3rd party form was submitted inside an iframe.
The event needed to be fired from the parent container and go through Google Tag Manager.

The solution was to use postMessage to send a JSON stringified object from the iframe to the parent window, like so:

<script type="text/javascript">

try {
	let gaParams = {
		'event':'iframeTestPageLoad', 
		'eventCategory':'Contact Form', 
		'eventAction':'Newsletter Signup Form TEST3', 
		'eventLabel':'discoverready.com/subscribe TEST3'
	};
	parent.postMessage(JSON.stringify(gaParams), "https://www.theparentdomain.com/");
} catch (e) {
	window.console && window.console.log(e);
}

</script>
Posting Message from inside the iFrame.

When this message was received by a listener in the parent container it was JSON.parsed back into an object and the parameters added to the GTM datalayer. For this scenario we only needed to check if the postMessage was a string.

<script type="text/javascript">
	
	// Some IE compatibility
	let eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
	let eventer = window[eventMethod];
	let messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
	
	// Listen to message from child window
	eventer(messageEvent,function(e) {
		if ( typeof e.data === 'string') {
	  		//console.log('parent message: ', e.data);
			let eventParams = JSON.parse( e.data );
			//console.log( eventParams );
			dataLayer.push( eventParams );
	  	}
	},false);

</script>
Listener in the parent frame and pushing to GTM datalayer.

I then had the pleasure of setting up the trigger in GTM, creating the new GTM custom variables and a new GTM tag that used the parameters defined in the iframe originally to fire an Analytics event.

Here’s the GTM tag taking the custom variables I created to correspond with the ones I was adding in the GTM dataLayer.

Was a lot of moving parts but very satisfying to see it all come together and work as requested!