forked from fed/react-router-ga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (76 loc) · 2.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// @flow
import * as React from 'react';
import { withRouter } from 'react-router-dom';
import type { Location, RouterHistory } from 'react-router-dom';
type Props = {
id: string, // Google Analytics Tracking ID
basename: string,
debug: boolean,
trackPathnameOnly: boolean,
children?: React.Node,
location: Location,
history: RouterHistory,
domains: string[]
};
class ReactRouterGA extends React.Component<Props> {
constructor(props) {
super(props);
this.sendPageView = this.sendPageView.bind(this);
this.initialize = this.initialize.bind(this);
this.initialize(props.id);
}
componentDidMount() {
this.sendPageView(this.props.location);
this.props.history.listen(this.sendPageView);
}
initialize() {
if (!this.props.id) {
console.error('[react-router-ga] Tracking ID is required.');
return;
}
// Check if window exists for static compiling
if (typeof window === "undefined") {
return;
}
// Load Google Analytics
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
// Initialize Google Analytics
if(this.props.domains && this.props.domains.length > 0) {
window.ga('create', this.props.id, 'auto', { allowLinker: true });
window.ga('require', 'linker');
window.ga('linker:autoLink', this.props.domains);
} else {
window.ga('create', this.props.id, 'auto');
}
}
sendPageView(location: Location) {
// Do nothing if GA was not initialized due to a missing tracking ID.
if (!window.ga) {
return;
}
// Do nothing if trackPathnameOnly is enabled and the pathname didn't change.
if (this.props.trackPathnameOnly && location.pathname === this.lastPathname) {
return;
}
this.lastPathname = location.pathname;
// Sets the page value on the tracker. If a basename is provided, then it is prepended to the pathname.
const page = this.props.basename ? `${this.props.basename}${location.pathname}` : location.pathname;
window.ga('set', 'page', page);
// Sending the pageview no longer requires passing the page
// value since it's now stored on the tracker object.
window.ga('send', 'pageview');
if (this.props.debug) {
console.info(`[react-router-ga] Page view: ${page}`);
}
}
render() {
return this.props.children;
}
}
ReactRouterGA.defaultProps = {
debug: false
};
export default withRouter(ReactRouterGA);