GTM and external iframe

postMessage and dataLayer

Pushing dataLayer object from iframe on third party domain to the GTM on the parent site.

Sample dataLayer used:

{
 'event': 'buttonClick',
 'Button clicked': 'A'
}

In this example dataLayer object is pushed from iframe https://hardcode.biz/iframe.html to parent https://hardcode.no/postmessage-datalayer (this article).

Parent (this page)

<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
 if (event.origin == "https://hardcode.biz") {
  window.dataLayer.push(JSON.parse(event.data));
 }
}
</script>

<iframe src="https://hardcode.biz/iframe.html"></iframe>

The JavaScript above could be more conveniently delivered as a Custom HTML tag in GTM.

Iframe (from other domain)

<script>
function dlPushToParent(target,object) {
 if(target = new URL((parent !== window) ? document.referrer : document.location).origin) {
  window.parent.postMessage(JSON.stringify(object),target);
 }
}
</script>

<button onclick="dlPushToParent('https://hardcode.no', {'event': 'buttonClick','Button clicked': 'A'});">Button A</button>
<button onclick="dlPushToParent('https://hardcode.no', {'event': 'buttonClick','Button clicked': 'B'});">Button B</button>
<button onclick="dlPushToParent('https://hardcode.no', {'event': 'buttonClick','Button clicked': 'C'});">Button C</button>