File size: 7,751 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { getCurrentUser } from '@automattic/calypso-analytics';
import { loadScript } from '@automattic/load-script';
import isAkismetCheckout from 'calypso/lib/akismet/is-akismet-checkout';
import isJetpackCheckout from 'calypso/lib/jetpack/is-jetpack-checkout';
import isJetpackCloud from 'calypso/lib/jetpack/is-jetpack-cloud';
import { mayWeInitTracker, mayWeTrackByTracker } from '../tracker-buckets';
import {
	debug,
	TRACKING_IDS,
	FACEBOOK_TRACKING_SCRIPT_URL,
	GOOGLE_GTAG_SCRIPT_URL,
	BING_TRACKING_SCRIPT_URL,
	CRITEO_TRACKING_SCRIPT_URL,
	TWITTER_TRACKING_SCRIPT_URL,
	LINKED_IN_SCRIPT_URL,
	QUORA_SCRIPT_URL,
	OUTBRAIN_SCRIPT_URL,
	PINTEREST_SCRIPT_URL,
	GOOGLE_GTM_SCRIPT_URL,
	WPCOM_CLARITY_URI,
	REDDIT_TRACKING_SCRIPT_URL,
	WPCOM_REDDIT_PIXEL_ID,
} from './constants';
import { circularReferenceSafeJSONStringify } from './debug';
import { setup } from './setup';

export const loadTrackingScripts = attemptLoad( async () => {
	setup();

	const scripts = getTrackingScriptsToLoad();

	let hasError = false;
	for ( const src of scripts ) {
		try {
			// We use `await` to load each script one by one and allow the GUI to load and be responsive while
			// the trackers get loaded in a user friendly manner.
			await loadScript( src );
		} catch ( error ) {
			hasError = true;
			debug( 'loadTrackingScripts: [Load Error] a tracking script failed to load: ', error );
		}
		debug( 'loadTrackingScripts: [Loaded]', src );
	}

	if ( hasError ) {
		throw new Error( 'One or more tracking scripts failed to load' );
	}

	debug( 'loadTrackingScripts: load done' );

	initLoadedTrackingScripts();

	// uses JSON.stringify for consistency with recordOrder()
	debug(
		'loadTrackingScripts: dataLayer:',
		circularReferenceSafeJSONStringify( window.dataLayer, 2 )
	);

	return scripts;
} );

function getTrackingScriptsToLoad() {
	const scripts = [];

	if ( mayWeTrackByTracker( 'facebook' ) ) {
		scripts.push( FACEBOOK_TRACKING_SCRIPT_URL );
	}

	// The Gtag script needs to be loaded with an ID in the URL so we search for the first available one.
	const enabledGtags = [
		mayWeTrackByTracker( 'googleAds' ) && TRACKING_IDS.wpcomGoogleAdsGtag,
		mayWeTrackByTracker( 'floodlight' ) && TRACKING_IDS.wpcomFloodlightGtag,
	].filter( ( id ) => false !== id );
	if ( enabledGtags.length > 0 ) {
		scripts.push( GOOGLE_GTAG_SCRIPT_URL + enabledGtags[ 0 ] );
	}

	if ( mayWeTrackByTracker( 'bing' ) ) {
		scripts.push( BING_TRACKING_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'criteo' ) ) {
		scripts.push( CRITEO_TRACKING_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'quantcast' ) ) {
		scripts.push( quantcastAsynchronousTagURL() );
	}

	if ( mayWeTrackByTracker( 'twitter' ) ) {
		scripts.push( TWITTER_TRACKING_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'linkedin' ) ) {
		scripts.push( LINKED_IN_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'quora' ) ) {
		scripts.push( QUORA_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'outbrain' ) ) {
		scripts.push( OUTBRAIN_SCRIPT_URL );
	}

	if ( mayWeTrackByTracker( 'pinterest' ) ) {
		scripts.push( PINTEREST_SCRIPT_URL );
	}

	if ( mayWeInitTracker( 'googleTagManager' ) && isAkismetCheckout() ) {
		scripts.push( GOOGLE_GTM_SCRIPT_URL + TRACKING_IDS.akismetGoogleTagManagerId );
	}

	if ( mayWeInitTracker( 'googleTagManager' ) && ( isJetpackCloud() || isJetpackCheckout() ) ) {
		scripts.push( GOOGLE_GTM_SCRIPT_URL + TRACKING_IDS.jetpackGoogleTagManagerId );
	}

	if ( mayWeTrackByTracker( 'clarity' ) ) {
		scripts.push( WPCOM_CLARITY_URI );
	}

	if ( mayWeTrackByTracker( 'reddit' ) ) {
		scripts.push( REDDIT_TRACKING_SCRIPT_URL );
	}

	return scripts;
}

function initLoadedTrackingScripts() {
	// init Facebook
	if ( mayWeTrackByTracker( 'facebook' ) ) {
		initFacebook();
	}

	// init Bing
	if ( mayWeTrackByTracker( 'bing' ) ) {
		const bingConfig = {
			ti: TRACKING_IDS.bingInit,
			q: window.uetq,
		};

		if ( typeof UET !== 'undefined' ) {
			// bing's script creates the UET global for us
			window.uetq = new UET( bingConfig ); // eslint-disable-line
		}
	}

	// init Twitter
	if ( mayWeTrackByTracker( 'twitter' ) ) {
		if ( isJetpackCloud() || isJetpackCheckout() ) {
			window.twq( 'config', TRACKING_IDS.jetpackTwitterPixelId );
		} else {
			window.twq( 'init', TRACKING_IDS.twitterPixelId );
		}
	}

	// init Quora
	if ( mayWeTrackByTracker( 'quora' ) ) {
		window.qp( 'init', TRACKING_IDS.quoraPixelId );
	}

	// init Pinterest
	if ( mayWeTrackByTracker( 'pinterest' ) ) {
		const currentUser = getCurrentUser();
		const params = currentUser ? { em: currentUser.hashedPii.email } : {};
		window.pintrk( 'load', TRACKING_IDS.pinterestInit, params );
	}

	if ( mayWeTrackByTracker( 'reddit' ) ) {
		const params = {
			optOut: false,
			useDecimalCurrencyValues: true,
		};

		window.rdt( 'init', WPCOM_REDDIT_PIXEL_ID, params );
	}

	debug( 'loadTrackingScripts: init done' );
}

// Returns a function that has the following behavior:
// - when called, tries to call `loader` and returns a promise that resolves when load is finished
// - when `loader` is already in progress, don't issue two concurrent calls: wait for the first to finish
// - when `loader` fails, DON'T return a rejected promise. Instead, leave it unresolved and let the caller
//   wait, potentially forever. Next call to the loader function has a chance to succeed and resolve the
//   promise, for the current and all previous callers. That effectively implements a queue.
function attemptLoad( loader ) {
	let setLoadResult;
	let loadResult;
	let status = 'not-loading';

	function initiateLoad() {
		loadResult = new Promise( ( resolve ) => {
			setLoadResult = resolve;
		} );

		loader().then(
			( result ) => {
				status = 'loaded';
				setLoadResult( result );
			},
			() => {
				status = 'not-loading';
			}
		);
	}

	return ( reload = false ) => {
		if ( status === 'not-loading' || reload ) {
			if ( reload ) {
				status = 'not-loading';
			}
			initiateLoad();
		}
		return loadResult;
	};
}

/**
 * Returns the URL for Quantcast's Purchase Confirmation Tag
 * @see https://www.quantcast.com/help/guides/using-the-quantcast-asynchronous-tag/
 * @returns {string} The URL
 */
function quantcastAsynchronousTagURL() {
	const protocolAndSubdomain =
		document.location.protocol === 'https:' ? 'https://secure' : 'http://edge';

	return protocolAndSubdomain + '.quantserve.com/quant.js';
}

/**
 * Initializes the Facebook pixel.
 *
 * When the user is logged in, additional hashed data is being forwarded.
 * See https://developers.facebook.com/docs/facebook-pixel/pixel-with-ads/conversion-tracking#advanced_match
 */
function initFacebook() {
	let advancedMatching = {};
	const currentUser = getCurrentUser();

	if ( currentUser ) {
		advancedMatching = { em: currentUser.hashedPii.email };
	}

	debug( 'initFacebook', advancedMatching );

	// WP Facebook pixel
	window.fbq( 'init', TRACKING_IDS.facebookInit, advancedMatching );

	// Jetpack & Akismet Facebook pixel
	// Also initialize the FB pixel for Jetpack & Akismet.
	// However, disable auto-config for this secondary pixel ID.
	// See: <https://developers.facebook.com/docs/facebook-pixel/api-reference#automatic-configuration>
	if ( isJetpackCheckout() ) {
		window.fbq( 'set', 'autoConfig', false, TRACKING_IDS.facebookJetpackInit );
		window.fbq( 'init', TRACKING_IDS.facebookJetpackInit, advancedMatching );
		window.fbq( 'track', 'PageView' ); // When autoConfig=false, page view tracking must be manually triggered
	}
	if ( isAkismetCheckout() ) {
		window.fbq( 'set', 'autoConfig', false, TRACKING_IDS.facebookAkismetInit );
		window.fbq( 'init', TRACKING_IDS.facebookAkismetInit, advancedMatching );
		window.fbq( 'track', 'PageView' ); // When autoConfig=false, page view tracking must be manually triggered
	}
}