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