UNPKG

2.31 kBTypeScriptView Raw
1import * as React from 'react';
2import ImportRemote from '@shopify/react-import-remote';
3
4import {GaJSAnalytics} from './types';
5import {getRootDomain, noop} from './utilities';
6
7export 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
18export const SETUP_SCRIPT = `
19 window['_gaq'] = window['_gaq'] || [];
20`;
21
22export function setupWithDebugScript(account: String) {
23 // https://developers.google.com/analytics/devguides/collection/gajs/#disable
24 return `window['ga-disable-GA_${account}'] = true;${SETUP_SCRIPT}`;
25}
26
27export const GA_JS_SCRIPT = 'https://stats.g.doubleclick.net/dc.js';
28
29export 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
91interface WindowWithGaJSAnalytics extends Window {
92 _gaq: GaJSAnalytics;
93}
94
95function getLegacyAnalytics(window: Window) {
96 return (window as WindowWithGaJSAnalytics)._gaq;
97}