【问题标题】:How to use JS to scrape the page and push the variables into GTM data layers如何使用 JS 抓取页面并将变量推送到 GTM 数据层
【发布时间】:2017-12-20 18:26:03
【问题描述】:

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

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

注意:您可以忽略“ID”和“收入”。

$("#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>

【问题讨论】:

  • 看来您应该在each 函数中执行您的dataLayer.push。似乎每个 li 中的项目都有冲突的 id,这可能会也可能不会导致问题,但绝对不是最佳实践。
  • 嗨@James,你对ID 是正确的,那些应该是类。我为这个示例快速编写了 HTML,因为实际页面具有更复杂的结构,不适合在这里使用。我现在就改正错误。

标签: javascript jquery google-tag-manager google-datalayer


【解决方案1】:

在每个函数中单独构建您的产品数组,然后在 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
    }
  }
});

【讨论】:

  • 嗨@James,如果我们如上所述使用js推送数据。我们是否应该期望推送到GTM的数据显示在GTM google chrome add on中?我们尝试了这个选项,我们可以看到在 chrome 的开发人员工具中的网络选项卡中触发的事件,但在 google chrome GTM 插件中没有。所以想知道这是否会显示?请指教。
猜你喜欢
  • 2014-01-27
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多