2017-08-02 67 views
0

我在写一个Javascript函数,它将成为Google跟踪代码管理器中的一个标记。我可以在Google跟踪代码管理器中观察数据层变量的变化吗?

它被加载到我最小控制的SPA上。

每当用户点击,我用的是GTM功能的一些数据推送到数据层,例如:

var someEventIsTriggered = function(e) { 
     var target = $('input#watched'); 

     // Trigger a generic "gtm.click" event on every click 
     dataLayer.push({ 
      "event": "gtm.customEvent", 
      "gtm.customWatchedVariable": target.val() 
     }); 
}; 

每到这个被触发时,它会推一个新的事件的数据层,并更新了gtm.customWatchedVariable的值。我现在要检查的是当前的gtm.customWatchedVariable与最后的gtm.customWatchedVariable不同,然后在GTM发生更改时触发一个触发器。

我该怎么做?

回答

0

感谢@维克多leontyev,指着我对答案。

我没有意识到你可以像对待其他数组一样对待dataLayer对象。所以我的代码现在看起来像这样:

var someEventIsTriggered = function(e) { 
    var target = $('input#watched'); 
    var lastEvent = dataLayer 
         .filter(function (e) { return e.event === 'gtm.customEvent'; }) 
         .pop(); 
    var lastValue = lastEvent instanceof Object 
         ? lastEvent["gtm.customWatchedVariable"] 
         : false; 

    // Trigger a generic "gtm.click" event on every click 
    dataLayer.push({ 
     "event": "gtm.customEvent", 
     "gtm.customWatchedVariable": target.val() 
    }); 

    if (lastValue !== target.val()) { 
     // Do the thing. 
    } 

}; 

谢谢!

1

这个js是检查是否在数据层对象最后gtm.customWatchedVariable变量是不同的:

var someEventIsTriggered = function(e) { 
    var target = $('input#watched'); 

    dataLayer.push({ 
     "event": "gtm.customEvent", 
     "gtm.customWatchedVariable": target.val() 
    }); 

    var customWatcherVar = dataLayer.filter(function(e){ return typeof(e["gtm.customWatchedVariable"]) != 'undefined';}); 
    var prevDatalayer = customWatcherVar[customWatcherVar.length-2]; 
    var newDatalayer = customWatcherVar[customWatcherVar.length-1]; 
    var prevVal = null; 
    var newVal = null; 
    if (prevDatalayer!=null) 
    { 
     prevVal = prevDatalayer["gtm.customWatchedVariable"]; 
    } 
    if (newDatalayer!=null) 
    { 
     newVal = newDatalayer["gtm.customWatchedVariable"]; 
    } 
    if (prevVal != newVal) 
    { 
     // Push another datalayer, because gtm.customWatchedVariable changed 
    } 

}; 
+0

谢谢!我没有意识到你可以像对待一个普通的旧的Javascript数组一样对待dataLayer。更优雅的做法是将最后一个元素推向新的元素。 – haz

+0

如果它为你工作,你能否接受我的答案 –

相关问题