1 | import * as React from 'react';
|
2 | import ImportRemote from '@shopify/react-import-remote';
|
3 |
|
4 | import {GaJSAnalytics} from './types';
|
5 | import {getRootDomain, noop} from './utilities';
|
6 |
|
7 | export interface Props {
|
8 | account: string;
|
9 | domain: string;
|
10 | nonce?: string;
|
11 | devId?: string;
|
12 | allowLinker?: boolean;
|
13 | allowHash?: boolean;
|
14 | set?: any[][];
|
15 | onLoad?(analytics: GaJSAnalytics): void;
|
16 | disableTracking?: boolean;
|
17 | }
|
18 |
|
19 | export const SETUP_SCRIPT = `
|
20 | window['_gaq'] = window['_gaq'] || [];
|
21 | `;
|
22 |
|
23 | export function setupWithDebugScript(account: String) {
|
24 |
|
25 | return `window['ga-disable-${account}'] = true;${SETUP_SCRIPT}`;
|
26 | }
|
27 |
|
28 | export const GA_JS_SCRIPT = 'https://stats.g.doubleclick.net/dc.js';
|
29 |
|
30 | export default class GaJSGoogleAnalytics extends React.PureComponent<
|
31 | Props,
|
32 | never
|
33 | > {
|
34 | render() {
|
35 | const {account, disableTracking, nonce} = this.props;
|
36 |
|
37 | return (
|
38 | <>
|
39 | <script
|
40 | id="google-analytics-gtag-script"
|
41 | dangerouslySetInnerHTML={{
|
42 | __html: disableTracking
|
43 | ? setupWithDebugScript(account)
|
44 | : SETUP_SCRIPT,
|
45 | }}
|
46 | nonce={nonce}
|
47 | />
|
48 | <ImportRemote
|
49 | preconnect
|
50 | source={GA_JS_SCRIPT}
|
51 | nonce={nonce}
|
52 | getImport={getLegacyAnalytics}
|
53 | onError={noop}
|
54 | onImported={this.setAnalytics}
|
55 | />
|
56 | </>
|
57 | );
|
58 | }
|
59 |
|
60 | private setAnalytics = (googleAnalytics: GaJSAnalytics) => {
|
61 | const {
|
62 | account,
|
63 | domain,
|
64 | devId,
|
65 | allowLinker,
|
66 | allowHash,
|
67 | set: setVariables = [],
|
68 | onLoad,
|
69 | } = this.props;
|
70 |
|
71 | googleAnalytics.push(['_setAccount', account]);
|
72 | googleAnalytics.push(['_setDomainName', getRootDomain(domain)]);
|
73 |
|
74 | if (devId && devId.length > 0) {
|
75 | googleAnalytics.push(['_addDevId', devId]);
|
76 | }
|
77 |
|
78 | if (allowLinker !== undefined) {
|
79 | googleAnalytics.push(['_setAllowLinker', allowLinker]);
|
80 | }
|
81 |
|
82 | if (allowHash !== undefined) {
|
83 | googleAnalytics.push(['_setAllowHash', allowHash]);
|
84 | }
|
85 |
|
86 | for (const variable of setVariables) {
|
87 | googleAnalytics.push(['_setCustomVar', ...variable]);
|
88 | }
|
89 |
|
90 | if (onLoad) {
|
91 | onLoad(googleAnalytics);
|
92 | }
|
93 | };
|
94 | }
|
95 |
|
96 | interface WindowWithGaJSAnalytics extends Window {
|
97 | _gaq: GaJSAnalytics;
|
98 | }
|
99 |
|
100 | function getLegacyAnalytics(window: Window) {
|
101 | return (window as WindowWithGaJSAnalytics)._gaq;
|
102 | }
|