简体   繁体   中英

JavaScript listen for _gaq.push?

I've got a widget that injects javascript code into my users website. Now I would like to add the ability to listen for the Google Analytics _addTrans call.

Example of the call to 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.

Is it possible for my script to also receive the push event to the _gaq object?

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. 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.

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 .

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. 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.

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);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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