1
/*
2
 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5
 * the License. A copy of the License is located at
6
 *
7
 *     http://aws.amazon.com/apache2.0/
8
 *
9
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11
 * and limitations under the License.
12
 */
13

14
import { pageViewTrackOpts } from '../types';
15 1
import { MethodEmbed } from '../utils/MethodEmbed';
16 1
import { ConsoleLogger as Logger, JS } from '@aws-amplify/core';
17

18 1
const logger = new Logger('PageViewTracker');
19 1
const PREV_URL_KEY = 'aws-amplify-analytics-prevUrl';
20

21 1
const getUrl = () => {
22 1
	if (!JS.browserOrNode().isBrowser) return '';
23 1
	else return window.location.origin + window.location.pathname;
24
};
25

26 1
const defaultOpts: pageViewTrackOpts = {
27
	enable: false,
28
	provider: 'AWSPinpoint',
29
	getUrl,
30
};
31

32 1
export class PageViewTracker {
33
	private _config: pageViewTrackOpts;
34
	private _tracker;
35
	private _hasEnabled;
36

37
	constructor(tracker, opts) {
38 1
		logger.debug('initialize pageview tracker with opts', opts);
39 1
		this._config = Object.assign({}, defaultOpts, opts);
40 1
		this._tracker = tracker;
41 1
		this._hasEnabled = false;
42 1
		this._trackFunc = this._trackFunc.bind(this);
43

44 1
		if (this._config.type === 'SPA') {
45 1
			this._pageViewTrackSPA();
46
		} else {
47 1
			this._pageViewTrackDefault();
48
		}
49
	}
50

51 1
	public configure(opts?: pageViewTrackOpts) {
52 1
		Object.assign(this._config, opts);
53

54
		// if spa, need to remove those listeners if disabled
55 1
		if (this._config.type === 'SPA') {
56 1
			this._pageViewTrackSPA();
57
		}
58

59 1
		return this._config;
60
	}
61

62 1
	private _isSameUrl() {
63 1
		const prevUrl = sessionStorage.getItem(PREV_URL_KEY);
64 1
		const curUrl = this._config.getUrl();
65

66 1
		if (prevUrl === curUrl) {
67 1
			logger.debug('the url is same');
68 1
			return true;
69 1
		} else return false;
70
	}
71

72 1
	private async _pageViewTrackDefault() {
73 1
		if (
74 1
			!JS.browserOrNode().isBrowser ||
75
			!window.addEventListener ||
76
			!window.sessionStorage
77
		) {
78 1
			logger.debug('not in the supported web enviroment');
79 1
			return;
80
		}
81 1
		const url = this._config.getUrl();
82 1
		const customAttrs =
83 1
			typeof this._config.attributes === 'function'
84 0
				? await this._config.attributes()
85 1
				: this._config.attributes;
86 1
		const attributes = Object.assign(
87
			{
88
				url,
89
			},
90
			customAttrs
91
		);
92

93 1
		if (this._config.enable && !this._isSameUrl()) {
94 0
			this._tracker(
95
				{
96 1
					name: this._config.eventName || 'pageView',
97
					attributes,
98
				},
99
				this._config.provider
100
			).catch(e => {
101 0
				logger.debug('Failed to record the page view event', e);
102
			});
103 0
			sessionStorage.setItem(PREV_URL_KEY, url);
104
		}
105
	}
106

107 1
	private async _trackFunc() {
108 1
		if (
109 1
			!JS.browserOrNode().isBrowser ||
110
			!window.addEventListener ||
111
			!history.pushState ||
112
			!window.sessionStorage
113
		) {
114 0
			logger.debug('not in the supported web enviroment');
115 0
			return;
116
		}
117

118 1
		const url = this._config.getUrl();
119 1
		const customAttrs =
120 1
			typeof this._config.attributes === 'function'
121 0
				? await this._config.attributes()
122 1
				: this._config.attributes;
123 1
		const attributes = Object.assign(
124
			{
125
				url,
126
			},
127
			customAttrs
128
		);
129

130 1
		if (!this._isSameUrl()) {
131 1
			this._tracker(
132
				{
133 1
					name: this._config.eventName || 'pageView',
134
					attributes,
135
				},
136
				this._config.provider
137
			).catch(e => {
138 0
				logger.debug('Failed to record the page view event', e);
139
			});
140 1
			sessionStorage.setItem(PREV_URL_KEY, url);
141
		}
142
	}
143

144 1
	private _pageViewTrackSPA() {
145 1
		if (
146 1
			!JS.browserOrNode().isBrowser ||
147
			!window.addEventListener ||
148
			!history.pushState
149
		) {
150 1
			logger.debug('not in the supported web enviroment');
151 1
			return;
152
		}
153

154 1
		if (this._config.enable && !this._hasEnabled) {
155 1
			MethodEmbed.add(history, 'pushState', this._trackFunc);
156 1
			MethodEmbed.add(history, 'replaceState', this._trackFunc);
157 1
			window.addEventListener('popstate', this._trackFunc);
158 1
			this._trackFunc();
159 1
			this._hasEnabled = true;
160
		} else {
161 1
			MethodEmbed.remove(history, 'pushState');
162 1
			MethodEmbed.remove(history, 'replaceState');
163 1
			window.removeEventListener('popstate', this._trackFunc);
164 1
			this._hasEnabled = false;
165
		}
166
	}
167 1
}
168

169
/**
170
 * @deprecated use named import
171
 */
172 1
export default PageViewTracker;

Read our documentation on viewing source code .

Loading