[英]JavaScript listen for _gaq.push?
我有一個小部件,可將javascript代碼注入我的用戶網站。 現在,我想添加偵聽Google Analytics(分析) _addTrans
調用的功能。
致電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
是Google Analytics(分析)提供的對象。
我的腳本是否也可能接收到_gaq對象的push事件?
我努力了:
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);
}
}
};
它可以工作,但是Google Analytics(分析)現在不再能夠跟蹤轉化。 看來我要覆蓋它。 任何想法如何做到這一點?
您要保存原始的push
函數,然后在覆蓋的末尾調用它。
var originalPush = window._gaq.push;
window._gaq.push = function () {
// do something else
...
// then call the original function with the same args
originalPush(arguments);
};
供將來參考,這被稱為Monkey Patching 。
根據您的實現,這可能會對Google Analytics(分析)產生不利影響,但您可以嘗試將對GA對象的引用從_gaq
更改為另一個變量,然后接管_gaq
變量以供自己使用。 然后,您可以重新定義_gaq.push()
函數,以使其(1)觸發新變量上的原始push()
方法,以及(2)觸發您自己的自定義事件處理程序。
例:
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.