본문 바로가기

English/Some Dev Stuff

[dataLayer] Implementing GA4 for E-commerce: A Guide for iframe-Structured Website

The other day, I ran into someone who was a senior during my college days. It was a rather unusual encounter, taking place on the bus I was taking for the first time. 

We exchanged business cards, and I learned that he is currently a team leader at a company that was once a client I worked with (the first client in the company I'm currently working for).

He mentioned that the developer I worked with is now closely collaborating with him!

I remember that their website utilizes an i-framed structure, and with those memories in mind, I'm writing this post to revive the related experiences.

Their product-related pages are within an iframe page under the parent page, and the GTM script is present only on the parent page. In other words, for tracking data, the parent page needs to receive data from the child page.

The iframe page sends data to the parent page as follows:

<script>
try {
    var postObject = {
        event: 'purchase',
        data: {
            'coupon': 'string_value',
            'currency': 'string_value',
            'shipping': 'string_value',
            'transaction_id': 'string_value',
            'value': 'integer_value', 
            'items': [
                {
                    'item_id': 'string_value',
                    'item_name': 'string_value',
                    'item_variant': 'string_value',
                    'price': 'float_value',
                    'quantity': 'integer_value',
                }
            ]
        }
    };
    parent.postMessage(postObject, 'https://parent.alcolrithmhub.com');
} catch(e) {
   window.console && window.console.log(e);
}
</script>

 

On the parent page, the following script receives data from the iframe page:

<script>
window.addEventListener("message", (event) => {
   if (event.data && event.data.event === "purchase") {
     var data = event.data;
   
     dataLayer.push({
       'event': 'purchase',
       'ecommerce': {
         'coupon': data.data.coupon,
         'currency': data.data.currency,
         'shipping': data.data.shipping,
         'transaction_id': data.data.transaction_id,
         'value': data.data.value, 
         'items': [
           {
                'item_id': data.data.item_id,
                'item_name': data.data.item_name,
                'item_variant': data.data.item_variant,
                'price': data.data.price,
                'quantity': data.data.quantity
           },
           {
             {{variable_key}}: {{variable_value}}
           }
         ]
       }
     });
   }
});
</script>

With the script provided above, we can successfully collect data, and the results can be observed as follows.