简体   繁体   English

JavaScript收听_gaq.push吗?

[英]JavaScript listen for _gaq.push?

I've got a widget that injects javascript code into my users website. 我有一个小部件,可将javascript代码注入我的用户网站。 Now I would like to add the ability to listen for the Google Analytics _addTrans call. 现在,我想添加侦听Google Analytics(分析) _addTrans调用的功能。

Example of the call to Google Analytics: 致电Google Analytics(分析)的示例:

<a onclick=" _gaq.push(['_addTrans',
    '1234',           // transaction ID - required
    'Acme Clothing',  // affiliation or store name
    '11.99',          // total - required
    '1.29',           // tax
    '5',              // shipping
    'San Jose',       // city
    'California',     // state or province
    'USA'             // country
  ]);" href="#">CONVERSION</a>

_gaq is an object supplied by Google Analytics. _gaq是Google Analytics(分析)提供的对象。

Is it possible for my script to also receive the push event to the _gaq object? 我的脚本是否也可能接收到_gaq对象的push事件?

I have tried: 我努力了:

if (window._gaq) {
    for (var i = 0; i < _gaq.length; i++) {     
        var method = _gaq[i].shift();
        console.log(method);
    }
};

window._gaq = {
    push: function() {
        try {
            var args = Array.prototype.slice.call(arguments, 0);
            console.log(args);
        }
        catch(err) { 
            console.log(err);
        }  
    }
};

It works but Google Analytics is now not able to track conversions anymore. 它可以工作,但是Google Analytics(分析)现在不再能够跟踪转化。 It seems I am overriding it. 看来我要覆盖它。 Any ideas how this could be done? 任何想法如何做到这一点?

You want to save the original push function and then call it at the end of your override. 您要保存原始的push函数,然后在覆盖的末尾调用它。

var originalPush = window._gaq.push;
window._gaq.push = function () {
  // do something else
  ...
  // then call the original function with the same args
  originalPush(arguments);
};

For future reference, this is known as Monkey Patching . 供将来参考,这被称为Monkey Patching

This may have an adverse effect on Google Analytics depending on your implementation, but you can try changing the reference to the GA object from _gaq to another variable, and then take over the _gaq variable for your own use. 根据您的实现,这可能会对Google Analytics(分析)产生不利影响,但您可以尝试将对GA对象的引用从_gaq更改为另一个变量,然后接管_gaq变量以供自己使用。 Then, you can redefine the _gaq.push() function so that it (1) triggers the original push() method on the new variable, and (2) triggers your own custom event handler. 然后,您可以重新定义_gaq.push()函数,以使其(1)触发新变量上的原始push()方法,以及(2)触发您自己的自定义事件处理程序。

Example: 例:

var _gaq_actual = _gaq;
_gaq = {
    push: function(args) {
        // First, call the push() method on the "actual" GA object.
        _gaq_actual.push(args);
        // Now, do what you want with the args here. (Or, you could do this first.)
        customMethod(args);
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM