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:
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.
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!