来自一个元素的dataLayer.push会破坏另一个元素的dataLayer.push

时间:2018-01-04 10:52:23

标签: html wordpress google-analytics google-tag-manager google-datalayer

我正在建造WP website using DIVI theme。应该被推入dataLayer的标签卡在某个地方,默认为"未设置"值。

为了推动我使用脚本的值:

<script>
    function init() {
        dataLayer.push({'sectionLabel': 'Test section'});
    }
    window.onload = init;
</script>

触发:

<p class="GASectionVisible"> 

适用于isolation但不适用于main website

现在有趣的部分:

我在同一页面上的切换上实现了非常相似的标记 - 只有在打开切换后才会触发它们以显示带触发类的内容。它们工作得很好,但我认为它们会以某种方式破坏dataLayer.push从新元素 - 标题。当我将标题中的完全相同的代码粘贴到全新的空白页面时,它们会正确触发并推送信息并按预期传递值。当我将他们的精确副本粘贴到我的网站上时,标签仍会触发,但会显示标签&#34;未设置&#34;。

我认为唯一的解决方法是将触发元素和脚本放在单独的页面上,然后通过iFrame将其嵌入主站点。它可以工作,但我不能在我需要跟踪的所有元素上做到这一点。

1 个答案:

答案 0 :(得分:0)

由于您在custom.min.js中覆盖了http://www.wro.place/smart-bedroom/函数,因此它未在onload页面上触发的问题。这意味着下面的代码永远不会触发,因为它被覆盖了。

<script>
  function init() {
    dataLayer.push({'sectionLabel': 'Test section'});
  }
  window.onload = init;
</script>`

正确的方法是

document.addEventListener('DOMContentLoaded', function () {
    dataLayer.push({'sectionLabel': 'Test section'});
}, false);

<强>更新 根据评论中的讨论,新的解决方案是:

var firedSections = []
window.dataLayer = window.dataLayer || [];
window.addEventListener('scroll', function() { 
    var sections = document.querySelectorAll('.et_pb_section');
    for(i=0;i<sections.length;i++)
    {
        if (firedSections.indexOf(i) == -1 && checkVisible(sections[i])) {
          firedSections.push(i)
          dataLayer.push({'sectionLabel': 'Number '+i});
        }
    }
});


function checkVisible(elm) {
    var rect = elm.getBoundingClientRect();
    var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
    return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

您需要在页面上添加此代码一次,一旦您滚动页面,它将进入数据层。