Search code examples
javascriptgoogle-tag-manageruniversal-analyticsenhanced-ecommerce

Google tag manager and advanced ecommerce - transaction products


I'm trying to configure advanced ecommerce analytics to read transaction data from an order confirmation page.

I'm scraping the data from the Dom elements since this is the only option available to me.

I'm able to read fields for transactionId, transactionTotal, transactionShipping etc but am not able to read transactionProducts. (I can only ever read 1 product, but no more if there are multiple products in the order).

My data layer has been added as a Custom HTML tag like so -

<script>      
window.dataLayer = window.dataLayer || []  
    dataLayer.push({
        'transactionId': {{transactionId}},
        'transactionAffiliation': 'Company name',    
        'transactionTotal': {{transactionTotal}},
        'transactionTax': 0,
        'transactionShipping': {{transactionShipping}},
        'transactionProducts': [{
            'sku':  {{productCode}},
            'name': {{transactionName}},
            'category': 'Generic category',
            'price': {{transactionPrice}},
            'quantity': {{transactionQuantity}}
        }]
    });
</script>

The fields are custom JavaScript variables.

For example -

TransactionId -

function() {
    var transactionId = document.querySelector([id*='OrderNumberValue']").textContent;
return transactionId;
}

Once the tag is fired on the confirmation page the data layer looks like so (as you can see, only 1 transaction product is returned when there are 2 products in the order) -

Window Loaded:
    {event: 'gtm.load'}
    transactionId: '1000001',
    transactionAffiliation: 'Company name',
    transactionTotal: '10.00',
    transactionTax: 0,
    transactionShipping: '0.00',
    transactionProducts: [
    {
        sku: 'SAMPLE1',
        name: 'Sample product',
        category: 'Generic category',
        price: '5.00',
        quantity: '1'
    }]
}
{gtm.start: 1474472447660, event: 'gtm.js'}

Would really appreciate any advice.

Thanks


Solution

  • That's not really answerable as long as you do not show how the HTML for you products look, but basically you'd use Document.querySelectorAll on the elements that contain the products and then iterate through the results and pick the values from the inner elements for each indivdual result. Assign to a (temporary) product object, add to your transactionproducts, and so on for each iteration.

    var results= document.querySelectorAll('.product');
    
    transactionProducts = [];
    for (i = 0; i < results.length; ++i) {
     result = results[i];
     tmp = {};
     tmp.price = result.querySelector('.sku').textContent;
     tmp.price = result.querySelector('.price').textContent;
     transactionProducts.push(tmp);
    }
    

    Not really tested or anything (and there are certainly more elegant ways to iterate nodelists), but this should give you an idea.