我正在编写一个Javascript函数,它将成为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 :(得分:1)
这个JS正在检查datalayer对象中的最后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
}
};
答案 1 :(得分:0)
感谢@ victor-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.
}
};
谢谢!