我的DOM中的Google Analytics像素在哪里?

时间:2015-07-17 20:58:38

标签: javascript google-analytics

如何使用JavaScript识别Google Analytics像素(或任何像素)已发送,并包含我正在寻找的网址参数?

我想,因为它是一个跟踪像素,我可以在DOM中查找它,但它看起来并没有被插入过。

有人能想出一种方法来分析谷歌使用javascript(不是Chrome扩展程序)发出的网络请求吗?

类似

document.whenGooglePixelIsSentDoReallyCoolStuff(function(requestUrl){

});

1 个答案:

答案 0 :(得分:6)

一些事情:

1)跟踪信标并不总是像素。有时他们会使用XHR,有时会根据情况使用navigator.sendBeacon和/或您的跟踪器transport setting,所以如果您只是寻找像素,那么您可能正在寻找在错误的地方。

2)您不需要向DOM添加图像以使其发送请求。只需做document.createElement('img').src = "path/to/image.gif"即可。

3)您不需要使用Chrome扩展程序来调试Google Analytics,您只需加载debug version of the script而不是常规版本。

4)如果您确实不想使用Google Analytics的调试版本并希望以编程方式跟踪发送的内容,则可以覆盖sendHitTask并拦截点击次数在他们被发送之前。

更新(2015年7月21日)

您已经改变了问题的措辞,所以我会回答新的措辞,说您应该遵循我在上面#4中给出的建议。这里有一些代码适用于您假设的whenGooglePixelIsSentDoReallyCoolStuff函数:

document.whenGooglePixelIsSentDoReallyCoolStuff = function(callback) {

  // Pass the `qa` queue method a function to get acess to the default
  // tracker object created via `ga('create', 'UA-XXXX-Y', ...)`. 
  ga(function(tracker) {

    // Grab a reference to the default `sendHitTask` function.
    var originalSendHitTask = tracker.get('sendHitTask');

    // Override the `sendHitTask` to call the passed callback.
    tracker.set('sendHitTask', function(model) {

      // When the `sendHitTask` runs, get the hit payload,
      // which is formatted as a URL query string.
      var requestUrl = model.get('hitPayload')

      // Invoke the callback passed to `whenGooglePixelIsSentDoReallyCoolStuff`
      // If the callback returns `false`, don't send the hit. This allows you
      // to programmatically do something else based on the contents of the
      // request URL.
      if (callback(requestUrl)) {
        originalSendHitTask(model);
      }
    });
  });
};

请注意,您必须在创建智能设备后运行此功能,但在发送首次匹配之前。换句话说,您必须在以下两行代码之间运行它:

ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');