-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
gtag.js
61 lines (53 loc) · 1.62 KB
/
gtag.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
59
60
61
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import siteConfig from '@generated/docusaurus.config';
const {themeConfig} = siteConfig;
export default (function() {
if (!themeConfig.gtag) {
return null;
}
const {trackingID} = themeConfig.gtag;
if (process.env.NODE_ENV === 'development' && !trackingID) {
console.warn(
'You specified the `gtag` object in `themeConfig` but the `trackingID` field was missing. ' +
'Please ensure this is not a mistake.',
);
return null;
}
if (
process.env.NODE_ENV !== 'production' ||
!trackingID ||
typeof window === 'undefined'
) {
return null;
}
/* eslint-disable */
const $scriptEl = window.document.createElement('script');
$scriptEl.async = 1;
$scriptEl.src = `https://www.googletagmanager.com/gtag/js?id=${trackingID}`;
window.document.head.appendChild($scriptEl);
window.dataLayer = window.dataLayer || [];
function gtag() {
// Have to use `arguments` instead of spreading as there are
// other properties attached to it e.g. callee.
// The GA library requires usage of `arguments.
window.dataLayer.push(arguments);
}
// Expose globally.
window.gtag = gtag;
gtag('js', new Date());
gtag('config', trackingID);
/* eslint-enable */
return {
onRouteUpdate({location}) {
// Always refer to the variable on window in-case it gets overridden elsewhere.
window.gtag('config', trackingID, {
page_path: location.pathname,
});
},
};
})();