UNPKG

2.34 kBTypeScriptView Raw
1import * as React from 'react';
2import ImportRemote from '@shopify/react-import-remote';
3
4import {UniversalAnalytics} from './types';
5import {getRootDomain, noop} from './utilities';
6
7export interface Props {
8 account: string;
9 domain: string;
10 set?: {[key: string]: any};
11 onLoad?(analytics: UniversalAnalytics): void;
12 debug?: boolean;
13}
14
15export 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
23export const UNIVERSAL_GA_SCRIPT =
24 'https://www.google-analytics.com/analytics.js';
25
26export const UNIVERSAL_GA_DEBUG_SCRIPT =
27 'https://www.google-analytics.com/analytics_debug.js';
28
29export 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 // The debug version of the analytics.js library
71 // https://developers.google.com/analytics/devguides/collection/analyticsjs/debugging
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
87interface WindowWithUniversalAnalytics extends Window {
88 ga: UniversalAnalytics;
89}
90
91function getUniversalAnalytics(window: Window) {
92 return (window as WindowWithUniversalAnalytics).ga;
93}