如何使用JS抓取页面并将变量推送到GTM数据层

How to use JS to scrape the page and push the variables into GTM data layers

我正在尝试通过使用 Javascript 抓取页面来填充 Google 数据层数组。正如控制台确认的那样,下面的代码成功地遍历了 HTML 中列出的所有项目。我正在努力编写正确的 dataLayer.push 函数来推送所有三项,而不仅仅是下面代码示例中的一项。

有人可以帮忙解决这个问题吗?

注意:您可以忽略"ID"和"revenue"。

$("#theList li").each(function() {
  
  var $this=$(this);
  scrapeProductName=$this.find('.name').text();
  scrapeProductPrice=$this.find('.price').text();
  scrapeProductQuantity=$this.find('.quantity').text();
  
  console.log('product: ' +  scrapeProductName + '; price: ' + scrapeProductPrice + '; quantity: ' + scrapeProductQuantity);
  
});

dataLayer = [];

dataLayer.push( {
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': '11111111', 'revenue': '999.99'
      },
      'products': [
      
      // start product list
      
      {
        'name': scrapeProductName,
        'price': scrapeProductPrice,
        'quantity': scrapeProductQuantity
      }
      
      // end product list
      
      ]
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul id="theList">
  <li>
    <div class="name">banana</div>
    <div class="price">1.00</div>
    <div class="quantity">3</div>
  </li>
  <li>
    <div class="name">apple</div>
    <div class="price">2.00</div>
    <div class="quantity">5</div>
  </li>
  <li>
    <div class="name">pear</div>
    <div class="price">3.50</div>
    <div class="quantity">1</div>
  </li>
</ul>

在每个函数中分别构建您的产品数组,然后将其作为单个实体附加到 dataLayer.push 调用中:

var products = [];

$("#theList li").each(function() {

  var $this=$(this);
  scrapeProductName=$this.find('.name').text();
  scrapeProductPrice=$this.find('.price').text();
  scrapeProductQuantity=$this.find('.quantity').text();

  console.log('product: ' +  scrapeProductName + '; price: ' + scrapeProductPrice + '; quantity: ' + scrapeProductQuantity);

  products.push({name: scrapeProductName, price: scrapeProductPrice, quantity: scrapeProductQuantity});

});

dataLayer = [];

dataLayer.push( {
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': '11111111', 'revenue': '999.99'
      },
      'products': products
    }
  }
});