/
dualtracking.js
58 lines (53 loc) · 2.05 KB
/
dualtracking.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Universal Analytics Dual Tracking Plugin
*/
(function(){
function providePlugin(pluginName, pluginConstructor) {
var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
if (typeof ga == 'function') {
ga('provide', pluginName, pluginConstructor);
}
}
var DualTracking = function(tracker, config) {
this.tracker = tracker;
this.property = config.property,
this.isDebug = config.debug;
this.transport = config.transport || 'beacon';
};
/**
*
*/
DualTracking.prototype.doDualTracking = function() {
this.debugMessage('Initializing the dualtracking plugin for GA');
if(!this.property || !this.property.match(/^UA-([0-9]*)-([0-9]{1,2}$)/)){
this.debugMessage('dualtracking plugin: property id, needs to be set and have the following format UA-XXXXXXXX-YY');
return 0;
}else{
window.__gaDualTracking = {};
window.__gaDualTracking.property = this.property;
window.__gaDualTracking.transport = this.transport;
}
var originalSendHitTask = this.tracker.get('sendHitTask');
this.tracker.set('sendHitTask', function(model) {
var payLoad = model.get('hitPayload');
var data = (payLoad).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
data.tid = window.__gaDualTracking.property;
originalSendHitTask(model);
var newPayload = Object.keys(data).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]); }).join('&');
if(__gaDualTracking.transport=="image"){
var i=new Image(1,1);
i.src="https://www.google-analytics.com/collect"+"?"+newPayload;i.onload=function(){return;}
}else if(__gaDualTracking.transport=="beacon"){
navigator.sendBeacon("https://www.google-analytics.com/collect", newPayload);
}
});
}
/**
* Displays a debug message in the console, if debugging is enabled.
*/
DualTracking.prototype.debugMessage = function(message) {
if (!this.isDebug) return;
if (console) console.debug(message);
};
providePlugin('dualtracking', DualTracking);
})();