Search code examples
javascriptgoogle-analyticse-commercegoogle-tag-managergoogle-datalayer

How to push a second product into the data layer with GTM


I'm patching enhanced eccommerce reoprting code for Google analytics using Google Tag Manager - by screen scraping data for a checkout step in the process. The code look like this:

var els = document.querySelectorAll('div.field_cart');

Array.prototype.forEach.call(els,function(element){

dataLayer.push({
  'event': 'checkout',
  'ecommerce': {
      'checkout': {
        'actionField': {'step': 1, 'option': 'Visa'},
        'products': [{
            'id': $('div.field_cart')[0].innerText,
        'price': $('div.field_cart')[1].innerText.match(/[0-9]+/),
        'quantity': $('div.field_cart')[2].innerText
     }//,{}...//
    ]
  }
 });
})

the problem is that if there are is more than one item - the second ovewrites the first etc instead of getting pushed ... I'd like to know how to append a new product to the products object?


Solution

  • I turns out google tag manager rewired dataLayer.push() method to fire events and guard the dataLayer's size. A side effect is that it does not operate as expected. The way to overcome this issue was to push all the scraped product data into a javascript variable and once it was ready, to push that variable into the dataLayer as follows:

    function scrape2DL() {    
        dataLayer.push({'ecommerce.checkout.actionField': {step: 2}}); //action object
    
        var base = 0; 
        var products=[];
        while (base < $('div.field_cart').length/4) {
           products.push([{id: $('div.field_cart')[4 * base + 0].innerText, price: $('div.field_cart')[4 * base + 1].innerText.match(/[0-9]+/), quantity: $('div.field_cart')[4 * base + 2].innerText}]);
           base += 1;
        }//while 
        dataLayer.push({'ecommerce.checkout.products': products}); // add a product 
     }
     scrape2DL();
     dataLayer.push({event: 'checkout'});      // for GTM triggers
    

    However it turns out that it is possible to fetch the products from the datalayer into a javascript variable using the datalayer get method and subsequently append more products into it. However I ultimately avoided this aproach as it skips the event and size guard check wired into dataLayer.push().

    The folowing resources were of some help: