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