首页 文章

我可以在Google跟踪代码管理器中查看数据层变量的更改吗?

提问于
浏览
1

我正在编写一个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发生变化时触发触发器 .

我怎样才能做到这一点?

2 回答

  • 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
        }
    
    };
    
  • 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.
        }
    
    };
    

    谢谢!

相关问题