1 | import * as React from 'react';
|
2 | import ImportRemote from '@shopify/react-import-remote';
|
3 |
|
4 | import {UniversalAnalytics} from './types';
|
5 | import {getRootDomain, noop} from './utilities';
|
6 |
|
7 | export interface Props {
|
8 | account: string;
|
9 | domain: string;
|
10 | nonce?: string;
|
11 | set?: {[key: string]: any};
|
12 | onLoad?(analytics: UniversalAnalytics): void;
|
13 | debug?: boolean;
|
14 | disableTracking?: boolean;
|
15 | }
|
16 |
|
17 | export const SETUP_SCRIPT = `
|
18 | window['GoogleAnalyticsObject'] = 'ga';
|
19 | window['ga'] = window['ga'] || function() {
|
20 | (window['ga'].q = window['ga'].q || []).push(arguments);
|
21 | };
|
22 | window['ga'].l = 1 * new Date();
|
23 | `;
|
24 |
|
25 | export const UNIVERSAL_GA_SCRIPT =
|
26 | 'https://www.google-analytics.com/analytics.js';
|
27 |
|
28 | export const UNIVERSAL_GA_DEBUG_SCRIPT =
|
29 | 'https://www.google-analytics.com/analytics_debug.js';
|
30 |
|
31 | export default class UniversalGoogleAnalytics extends React.PureComponent<
|
32 | Props,
|
33 | never
|
34 | > {
|
35 | render() {
|
36 | const {debug, nonce} = this.props;
|
37 |
|
38 | return (
|
39 | <>
|
40 | <script
|
41 | id="google-analytics-universal-script"
|
42 | dangerouslySetInnerHTML={{__html: SETUP_SCRIPT}}
|
43 | nonce={nonce}
|
44 | />
|
45 | <ImportRemote
|
46 | preconnect
|
47 | source={debug ? UNIVERSAL_GA_DEBUG_SCRIPT : UNIVERSAL_GA_SCRIPT}
|
48 | nonce={nonce}
|
49 | getImport={getUniversalAnalytics}
|
50 | onError={noop}
|
51 | onImported={this.setAnalytics}
|
52 | />
|
53 | </>
|
54 | );
|
55 | }
|
56 |
|
57 | private setAnalytics = (googleAnalytics: UniversalAnalytics) => {
|
58 | const {
|
59 | account,
|
60 | domain,
|
61 | set: setVariables = {},
|
62 | onLoad,
|
63 | debug = false,
|
64 | disableTracking = false,
|
65 | } = this.props;
|
66 |
|
67 | const normalizedDomain = getRootDomain(domain);
|
68 | const options = {
|
69 | cookieDomain: normalizedDomain,
|
70 | legacyCookieDomain: normalizedDomain,
|
71 | allowLinker: true,
|
72 | };
|
73 |
|
74 | googleAnalytics('create', account, 'auto', options);
|
75 |
|
76 | if (debug || disableTracking) {
|
77 |
|
78 |
|
79 | googleAnalytics('set', 'sendHitTask', null);
|
80 | }
|
81 |
|
82 | for (const [key, value] of Object.entries(setVariables)) {
|
83 | googleAnalytics('set', key, value);
|
84 | }
|
85 |
|
86 | if (onLoad) {
|
87 | onLoad(googleAnalytics);
|
88 | }
|
89 | };
|
90 | }
|
91 |
|
92 | interface WindowWithUniversalAnalytics extends Window {
|
93 | ga: UniversalAnalytics;
|
94 | }
|
95 |
|
96 | function getUniversalAnalytics(window: Window) {
|
97 | return (window as WindowWithUniversalAnalytics).ga;
|
98 | }
|