我正在编写一个 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 发生变化时触发触发器。
我该怎么做?
最佳答案
此 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
}
};
关于javascript - 我可以在 Google 跟踪代码管理器中观察数据层变量的变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45453957/