swetrix 1.0.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,201 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Andrii Romasiun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ <img src="https://swetrix.com/assets/logo_blue.svg" alt="" height="100" />
2
+
1
3
  # Swetrix Tracking Script
2
4
 
3
5
  This repository contains the analytics script which is used at https://swetrix.com \
@@ -5,3 +7,6 @@ You can find the detailed documentation and use cases at our [docs page](https:/
5
7
 
6
8
  Feel free to contribute to the source code by opening a pull requests. \
7
9
  For any questions, you can open an issue ticket, refer to our [FAQs](https://swetrix.com/#faq) page or reach us at contact@swetrix.com
10
+
11
+ # Selfhosted API
12
+ If you are selfhosting the [Swetrix-API](https://github.com/Swetrix/swetrix-api), be sure to point the `apiUrl` parameter to: `https://yourapiinstance.com/log`
@@ -2,6 +2,7 @@ export interface LibOptions {
2
2
  debug?: boolean;
3
3
  disabled?: boolean;
4
4
  respectDNT?: boolean;
5
+ apiURL?: string;
5
6
  }
6
7
  export interface TrackEventOptions {
7
8
  ev: string;
@@ -13,18 +14,23 @@ export interface PageData {
13
14
  }
14
15
  export interface PageViewsOptions {
15
16
  unique?: boolean;
17
+ ignore?: Array<any>;
18
+ noHeartbeat?: boolean;
19
+ heartbeatOnBackground?: boolean;
16
20
  }
17
21
  export declare class Lib {
18
22
  private projectID;
19
23
  private options?;
20
24
  private pageData;
25
+ private pageViewsOptions;
21
26
  constructor(projectID: string, options?: LibOptions | undefined);
22
27
  track(event: TrackEventOptions): void;
23
- trackPageViews(options?: PageViewsOptions): object | undefined;
28
+ trackPageViews(options?: PageViewsOptions): void | object;
29
+ private heartbeat;
30
+ private checkIgnore;
24
31
  private trackPathChange;
25
32
  private trackPage;
26
33
  private debug;
27
34
  private canTrack;
28
- private submitData;
29
- private submitCustom;
35
+ private sendRequest;
30
36
  }
@@ -1,13 +1,14 @@
1
1
  import { isInBrowser, isLocalhost, isAutomated, getLocale, getTimezone, getReferrer, getUTMCampaign, getUTMMedium, getUTMSource, getPath, } from './utils';
2
- const host = 'https://api.swetrix.com/log';
2
+ const DEFAULT_API_HOST = 'https://api.swetrix.com/log';
3
3
  export class Lib {
4
4
  constructor(projectID, options) {
5
5
  this.projectID = projectID;
6
6
  this.options = options;
7
7
  this.pageData = null;
8
+ this.pageViewsOptions = null;
8
9
  this.trackPathChange = this.trackPathChange.bind(this);
10
+ this.heartbeat = this.heartbeat.bind(this);
9
11
  }
10
- // Tracks a custom event
11
12
  track(event) {
12
13
  if (!this.canTrack()) {
13
14
  return;
@@ -16,9 +17,8 @@ export class Lib {
16
17
  pid: this.projectID,
17
18
  ...event,
18
19
  };
19
- this.submitCustom(data);
20
+ this.sendRequest('custom', data);
20
21
  }
21
- // Tracks page views
22
22
  trackPageViews(options) {
23
23
  if (!this.canTrack()) {
24
24
  return;
@@ -26,20 +26,49 @@ export class Lib {
26
26
  if (this.pageData) {
27
27
  return this.pageData.actions;
28
28
  }
29
- let interval;
29
+ this.pageViewsOptions = options;
30
+ let hbInterval, interval;
30
31
  if (!options?.unique) {
31
32
  interval = setInterval(this.trackPathChange, 2000);
32
33
  }
34
+ if (!options?.noHeartbeat) {
35
+ setTimeout(this.heartbeat, 3000);
36
+ hbInterval = setInterval(this.heartbeat, 28000);
37
+ }
33
38
  const path = getPath();
34
39
  this.pageData = {
35
40
  path,
36
41
  actions: {
37
- stop: options?.unique ? () => { } : () => clearInterval(interval),
42
+ stop: () => {
43
+ clearInterval(interval);
44
+ clearInterval(hbInterval);
45
+ },
38
46
  },
39
47
  };
40
48
  this.trackPage(path, options?.unique);
41
49
  return this.pageData.actions;
42
50
  }
51
+ heartbeat() {
52
+ if (!this.pageViewsOptions?.heartbeatOnBackground && document.visibilityState === 'hidden') {
53
+ return;
54
+ }
55
+ const data = {
56
+ pid: this.projectID,
57
+ };
58
+ this.sendRequest('hb', data);
59
+ }
60
+ checkIgnore(path) {
61
+ const ignore = this.pageViewsOptions?.ignore;
62
+ if (Array.isArray(ignore)) {
63
+ for (let i = 0; i < ignore.length; ++i) {
64
+ if (ignore[i] === path)
65
+ return true;
66
+ if (ignore[i] instanceof RegExp && ignore[i].test(path))
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ }
43
72
  // Tracking path changes. If path changes -> calling this.trackPage method
44
73
  trackPathChange() {
45
74
  if (!this.pageData)
@@ -54,6 +83,8 @@ export class Lib {
54
83
  if (!this.pageData)
55
84
  return;
56
85
  this.pageData.path = pg;
86
+ if (this.checkIgnore(pg))
87
+ return;
57
88
  const data = {
58
89
  pid: this.projectID,
59
90
  lc: getLocale(),
@@ -65,7 +96,7 @@ export class Lib {
65
96
  unique,
66
97
  pg,
67
98
  };
68
- this.submitData(data);
99
+ this.sendRequest('', data);
69
100
  }
70
101
  debug(message) {
71
102
  if (this.options?.debug) {
@@ -73,6 +104,10 @@ export class Lib {
73
104
  }
74
105
  }
75
106
  canTrack() {
107
+ if (this.options?.disabled) {
108
+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');
109
+ return false;
110
+ }
76
111
  if (!isInBrowser()) {
77
112
  this.debug('Tracking disabled: script does not run in browser environment.');
78
113
  return false;
@@ -90,25 +125,12 @@ export class Lib {
90
125
  }
91
126
  return true;
92
127
  }
93
- submitData(body) {
94
- return fetch(host, {
95
- method: 'post',
96
- headers: {
97
- 'Accept': 'application/json',
98
- 'Content-Type': 'application/json',
99
- },
100
- body: JSON.stringify(body),
101
- });
102
- }
103
- submitCustom(body) {
104
- return fetch(`${host}/custom`, {
105
- method: 'post',
106
- headers: {
107
- 'Accept': 'application/json',
108
- 'Content-Type': 'application/json',
109
- },
110
- body: JSON.stringify(body),
111
- });
128
+ sendRequest(path, body) {
129
+ const host = this.options?.apiURL || DEFAULT_API_HOST;
130
+ const req = new XMLHttpRequest();
131
+ req.open('POST', `${host}/${path}`, true);
132
+ req.setRequestHeader('Content-Type', 'application/json');
133
+ req.send(JSON.stringify(body));
112
134
  }
113
135
  }
114
136
  //# sourceMappingURL=Lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Lib.js","sourceRoot":"","sources":["../../src/Lib.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAC1E,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,OAAO,GACpD,MAAM,SAAS,CAAA;AAsChB,MAAM,IAAI,GAAG,6BAA6B,CAAA;AAE1C,MAAM,OAAO,GAAG;IAGd,YAAoB,SAAiB,EAAU,OAAoB;QAA/C,cAAS,GAAT,SAAS,CAAQ;QAAU,YAAO,GAAP,OAAO,CAAa;QAF3D,aAAQ,GAAoB,IAAI,CAAA;QAGtC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACxD,CAAC;IAED,wBAAwB;IACxB,KAAK,CAAC,KAAwB;QAC5B,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAA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AAI,CAAC,CAAA;QACzC,GAAG,CAAC,gBAAgB,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAA;QACxD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IAChC,CAAC;CACF"}
@@ -66,23 +66,23 @@ var getPath = function () {
66
66
  return location.pathname || '';
67
67
  };
68
68
 
69
- var host = 'https://api.swetrix.com/log';
69
+ var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
70
70
  var Lib = /** @class */ (function () {
71
71
  function Lib(projectID, options) {
72
72
  this.projectID = projectID;
73
73
  this.options = options;
74
74
  this.pageData = null;
75
+ this.pageViewsOptions = null;
75
76
  this.trackPathChange = this.trackPathChange.bind(this);
77
+ this.heartbeat = this.heartbeat.bind(this);
76
78
  }
77
- // Tracks a custom event
78
79
  Lib.prototype.track = function (event) {
79
80
  if (!this.canTrack()) {
80
81
  return;
81
82
  }
82
83
  var data = __assign({ pid: this.projectID }, event);
83
- this.submitCustom(data);
84
+ this.sendRequest('custom', data);
84
85
  };
85
- // Tracks page views
86
86
  Lib.prototype.trackPageViews = function (options) {
87
87
  if (!this.canTrack()) {
88
88
  return;
@@ -90,20 +90,51 @@ var Lib = /** @class */ (function () {
90
90
  if (this.pageData) {
91
91
  return this.pageData.actions;
92
92
  }
93
- var interval;
93
+ this.pageViewsOptions = options;
94
+ var hbInterval, interval;
94
95
  if (!(options === null || options === void 0 ? void 0 : options.unique)) {
95
96
  interval = setInterval(this.trackPathChange, 2000);
96
97
  }
98
+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {
99
+ setTimeout(this.heartbeat, 3000);
100
+ hbInterval = setInterval(this.heartbeat, 28000);
101
+ }
97
102
  var path = getPath();
98
103
  this.pageData = {
99
104
  path: path,
100
105
  actions: {
101
- stop: (options === null || options === void 0 ? void 0 : options.unique) ? function () { } : function () { return clearInterval(interval); },
106
+ stop: function () {
107
+ clearInterval(interval);
108
+ clearInterval(hbInterval);
109
+ },
102
110
  },
103
111
  };
104
112
  this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);
105
113
  return this.pageData.actions;
106
114
  };
115
+ Lib.prototype.heartbeat = function () {
116
+ var _a;
117
+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {
118
+ return;
119
+ }
120
+ var data = {
121
+ pid: this.projectID,
122
+ };
123
+ this.sendRequest('hb', data);
124
+ };
125
+ Lib.prototype.checkIgnore = function (path) {
126
+ var _a;
127
+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;
128
+ if (Array.isArray(ignore)) {
129
+ for (var i = 0; i < ignore.length; ++i) {
130
+ if (ignore[i] === path)
131
+ return true;
132
+ if (ignore[i] instanceof RegExp && ignore[i].test(path))
133
+ return true;
134
+ }
135
+ }
136
+ return false;
137
+ };
107
138
  // Tracking path changes. If path changes -> calling this.trackPage method
108
139
  Lib.prototype.trackPathChange = function () {
109
140
  if (!this.pageData)
@@ -119,6 +150,8 @@ var Lib = /** @class */ (function () {
119
150
  if (!this.pageData)
120
151
  return;
121
152
  this.pageData.path = pg;
153
+ if (this.checkIgnore(pg))
154
+ return;
122
155
  var data = {
123
156
  pid: this.projectID,
124
157
  lc: getLocale(),
@@ -130,7 +163,7 @@ var Lib = /** @class */ (function () {
130
163
  unique: unique,
131
164
  pg: pg,
132
165
  };
133
- this.submitData(data);
166
+ this.sendRequest('', data);
134
167
  };
135
168
  Lib.prototype.debug = function (message) {
136
169
  var _a;
@@ -139,16 +172,20 @@ var Lib = /** @class */ (function () {
139
172
  }
140
173
  };
141
174
  Lib.prototype.canTrack = function () {
142
- var _a, _b, _c;
175
+ var _a, _b, _c, _d;
176
+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {
177
+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');
178
+ return false;
179
+ }
143
180
  if (!isInBrowser()) {
144
181
  this.debug('Tracking disabled: script does not run in browser environment.');
145
182
  return false;
146
183
  }
147
- if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.respectDNT) && ((_b = window.navigator) === null || _b === void 0 ? void 0 : _b.doNotTrack) === '1') {
184
+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {
148
185
  this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');
149
186
  return false;
150
187
  }
151
- if (!((_c = this.options) === null || _c === void 0 ? void 0 : _c.debug) && isLocalhost()) {
188
+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {
152
189
  return false;
153
190
  }
154
191
  if (isAutomated()) {
@@ -157,25 +194,13 @@ var Lib = /** @class */ (function () {
157
194
  }
158
195
  return true;
159
196
  };
160
- Lib.prototype.submitData = function (body) {
161
- return fetch(host, {
162
- method: 'post',
163
- headers: {
164
- 'Accept': 'application/json',
165
- 'Content-Type': 'application/json',
166
- },
167
- body: JSON.stringify(body),
168
- });
169
- };
170
- Lib.prototype.submitCustom = function (body) {
171
- return fetch(host + "/custom", {
172
- method: 'post',
173
- headers: {
174
- 'Accept': 'application/json',
175
- 'Content-Type': 'application/json',
176
- },
177
- body: JSON.stringify(body),
178
- });
197
+ Lib.prototype.sendRequest = function (path, body) {
198
+ var _a;
199
+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;
200
+ var req = new XMLHttpRequest();
201
+ req.open('POST', "".concat(host, "/").concat(path), true);
202
+ req.setRequestHeader('Content-Type', 'application/json');
203
+ req.send(JSON.stringify(body));
179
204
  };
180
205
  return Lib;
181
206
  }());
@@ -62,23 +62,23 @@ var getPath = function () {
62
62
  return location.pathname || '';
63
63
  };
64
64
 
65
- var host = 'https://api.swetrix.com/log';
65
+ var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
66
66
  var Lib = /** @class */ (function () {
67
67
  function Lib(projectID, options) {
68
68
  this.projectID = projectID;
69
69
  this.options = options;
70
70
  this.pageData = null;
71
+ this.pageViewsOptions = null;
71
72
  this.trackPathChange = this.trackPathChange.bind(this);
73
+ this.heartbeat = this.heartbeat.bind(this);
72
74
  }
73
- // Tracks a custom event
74
75
  Lib.prototype.track = function (event) {
75
76
  if (!this.canTrack()) {
76
77
  return;
77
78
  }
78
79
  var data = __assign({ pid: this.projectID }, event);
79
- this.submitCustom(data);
80
+ this.sendRequest('custom', data);
80
81
  };
81
- // Tracks page views
82
82
  Lib.prototype.trackPageViews = function (options) {
83
83
  if (!this.canTrack()) {
84
84
  return;
@@ -86,20 +86,51 @@ var Lib = /** @class */ (function () {
86
86
  if (this.pageData) {
87
87
  return this.pageData.actions;
88
88
  }
89
- var interval;
89
+ this.pageViewsOptions = options;
90
+ var hbInterval, interval;
90
91
  if (!(options === null || options === void 0 ? void 0 : options.unique)) {
91
92
  interval = setInterval(this.trackPathChange, 2000);
92
93
  }
94
+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {
95
+ setTimeout(this.heartbeat, 3000);
96
+ hbInterval = setInterval(this.heartbeat, 28000);
97
+ }
93
98
  var path = getPath();
94
99
  this.pageData = {
95
100
  path: path,
96
101
  actions: {
97
- stop: (options === null || options === void 0 ? void 0 : options.unique) ? function () { } : function () { return clearInterval(interval); },
102
+ stop: function () {
103
+ clearInterval(interval);
104
+ clearInterval(hbInterval);
105
+ },
98
106
  },
99
107
  };
100
108
  this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);
101
109
  return this.pageData.actions;
102
110
  };
111
+ Lib.prototype.heartbeat = function () {
112
+ var _a;
113
+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {
114
+ return;
115
+ }
116
+ var data = {
117
+ pid: this.projectID,
118
+ };
119
+ this.sendRequest('hb', data);
120
+ };
121
+ Lib.prototype.checkIgnore = function (path) {
122
+ var _a;
123
+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;
124
+ if (Array.isArray(ignore)) {
125
+ for (var i = 0; i < ignore.length; ++i) {
126
+ if (ignore[i] === path)
127
+ return true;
128
+ if (ignore[i] instanceof RegExp && ignore[i].test(path))
129
+ return true;
130
+ }
131
+ }
132
+ return false;
133
+ };
103
134
  // Tracking path changes. If path changes -> calling this.trackPage method
104
135
  Lib.prototype.trackPathChange = function () {
105
136
  if (!this.pageData)
@@ -115,6 +146,8 @@ var Lib = /** @class */ (function () {
115
146
  if (!this.pageData)
116
147
  return;
117
148
  this.pageData.path = pg;
149
+ if (this.checkIgnore(pg))
150
+ return;
118
151
  var data = {
119
152
  pid: this.projectID,
120
153
  lc: getLocale(),
@@ -126,7 +159,7 @@ var Lib = /** @class */ (function () {
126
159
  unique: unique,
127
160
  pg: pg,
128
161
  };
129
- this.submitData(data);
162
+ this.sendRequest('', data);
130
163
  };
131
164
  Lib.prototype.debug = function (message) {
132
165
  var _a;
@@ -135,16 +168,20 @@ var Lib = /** @class */ (function () {
135
168
  }
136
169
  };
137
170
  Lib.prototype.canTrack = function () {
138
- var _a, _b, _c;
171
+ var _a, _b, _c, _d;
172
+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {
173
+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');
174
+ return false;
175
+ }
139
176
  if (!isInBrowser()) {
140
177
  this.debug('Tracking disabled: script does not run in browser environment.');
141
178
  return false;
142
179
  }
143
- if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.respectDNT) && ((_b = window.navigator) === null || _b === void 0 ? void 0 : _b.doNotTrack) === '1') {
180
+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {
144
181
  this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');
145
182
  return false;
146
183
  }
147
- if (!((_c = this.options) === null || _c === void 0 ? void 0 : _c.debug) && isLocalhost()) {
184
+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {
148
185
  return false;
149
186
  }
150
187
  if (isAutomated()) {
@@ -153,25 +190,13 @@ var Lib = /** @class */ (function () {
153
190
  }
154
191
  return true;
155
192
  };
156
- Lib.prototype.submitData = function (body) {
157
- return fetch(host, {
158
- method: 'post',
159
- headers: {
160
- 'Accept': 'application/json',
161
- 'Content-Type': 'application/json',
162
- },
163
- body: JSON.stringify(body),
164
- });
165
- };
166
- Lib.prototype.submitCustom = function (body) {
167
- return fetch(host + "/custom", {
168
- method: 'post',
169
- headers: {
170
- 'Accept': 'application/json',
171
- 'Content-Type': 'application/json',
172
- },
173
- body: JSON.stringify(body),
174
- });
193
+ Lib.prototype.sendRequest = function (path, body) {
194
+ var _a;
195
+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;
196
+ var req = new XMLHttpRequest();
197
+ req.open('POST', "".concat(host, "/").concat(path), true);
198
+ req.setRequestHeader('Content-Type', 'application/json');
199
+ req.send(JSON.stringify(body));
175
200
  };
176
201
  return Lib;
177
202
  }());
package/dist/swetrix.js CHANGED
@@ -1 +1 @@
1
- !function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(o){"use strict";function i(t){return(t=location.search.match(t))&&t[2]||void 0}function e(){return location.pathname||""}var n=function(){return(n=Object.assign||function(t){for(var n,o=1,i=arguments.length;o<i;o++)for(var e in n=arguments[o])Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t}).apply(this,arguments)},a=/[?&](ref|source|utm_source)=([^?&]+)/,r=/[?&](utm_campaign)=([^?&]+)/,s=/[?&](utm_medium)=([^?&]+)/,c="https://api.swetrix.com/log",u=(t.prototype.track=function(t){this.canTrack()&&(t=n({pid:this.projectID},t),this.submitCustom(t))},t.prototype.trackPageViews=function(t){if(this.canTrack()){if(this.pageData)return this.pageData.actions;var n;null!=t&&t.unique||(n=setInterval(this.trackPathChange,2e3));var o=e();return this.pageData={path:o,actions:{stop:null!=t&&t.unique?function(){}:function(){return clearInterval(n)}}},this.trackPage(o,null==t?void 0:t.unique),this.pageData.actions}},t.prototype.trackPathChange=function(){var t;this.pageData&&(t=e(),this.pageData.path!==t&&this.trackPage(t,!1))},t.prototype.trackPage=function(t,n){void 0===n&&(n=!1),this.pageData&&(this.pageData.path=t,t={pid:this.projectID,lc:void 0!==navigator.languages?navigator.languages[0]:navigator.language,tz:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return}}(),ref:document.referrer||void 0,so:i(a),me:i(s),ca:i(r),unique:n,pg:t},this.submitData(t))},t.prototype.debug=function(t){var n;null!==(n=this.options)&&void 0!==n&&n.debug&&console.log("[Swetrix]",t)},t.prototype.canTrack=function(){var t,n;return"undefined"==typeof window?(this.debug("Tracking disabled: script does not run in browser environment."),!1):null!==(t=this.options)&&void 0!==t&&t.respectDNT&&"1"===(null===(n=window.navigator)||void 0===n?void 0:n.doNotTrack)?(this.debug("Tracking disabled: respecting user's 'Do Not Track' preference."),!1):!!(null!==(n=this.options)&&void 0!==n&&n.debug||"localhost"!==(null===location||void 0===location?void 0:location.hostname)&&"127.0.0.1"!==(null===location||void 0===location?void 0:location.hostname)&&""!==(null===location||void 0===location?void 0:location.hostname))&&(null===navigator||void 0===navigator||!navigator.webdriver||(this.debug("Tracking disabled: navigation is automated by WebDriver."),!1))},t.prototype.submitData=function(t){return fetch(c,{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)})},t.prototype.submitCustom=function(t){return fetch(c+"/custom",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)})},t);function t(t,n){this.projectID=t,this.options=n,this.pageData=null,this.trackPathChange=this.trackPathChange.bind(this)}o.LIB_INSTANCE=null,o.init=function(t,n){return o.LIB_INSTANCE||(o.LIB_INSTANCE=new u(t,n)),o.LIB_INSTANCE},o.track=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.track(t)},o.trackViews=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.trackPageViews(t)},Object.defineProperty(o,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(i){"use strict";function n(t){return(t=location.search.match(t))&&t[2]||void 0}function a(){return location.pathname||""}var e=function(){return(e=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var a in e=arguments[i])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t}).apply(this,arguments)},o=/[?&](ref|source|utm_source)=([^?&]+)/,r=/[?&](utm_campaign)=([^?&]+)/,s=/[?&](utm_medium)=([^?&]+)/,c=(t.prototype.track=function(t){this.canTrack()&&(t=e({pid:this.projectID},t),this.sendRequest("custom",t))},t.prototype.trackPageViews=function(t){if(this.canTrack()){if(this.pageData)return this.pageData.actions;var e,i;null!=(this.pageViewsOptions=t)&&t.unique||(i=setInterval(this.trackPathChange,2e3)),null!=t&&t.noHeartbeat||(setTimeout(this.heartbeat,3e3),e=setInterval(this.heartbeat,28e3));var n=a();return this.pageData={path:n,actions:{stop:function(){clearInterval(i),clearInterval(e)}}},this.trackPage(n,null==t?void 0:t.unique),this.pageData.actions}},t.prototype.heartbeat=function(){var t;(null!==(t=this.pageViewsOptions)&&void 0!==t&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},t.prototype.checkIgnore=function(t){var e,i=null===(e=this.pageViewsOptions)||void 0===e?void 0:e.ignore;if(Array.isArray(i))for(var n=0;n<i.length;++n){if(i[n]===t)return!0;if(i[n]instanceof RegExp&&i[n].test(t))return!0}return!1},t.prototype.trackPathChange=function(){var t;this.pageData&&(t=a(),this.pageData.path!==t&&this.trackPage(t,!1))},t.prototype.trackPage=function(t,e){void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,this.checkIgnore(t)||(t={pid:this.projectID,lc:void 0!==navigator.languages?navigator.languages[0]:navigator.language,tz:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return}}(),ref:document.referrer||void 0,so:n(o),me:n(s),ca:n(r),unique:e,pg:t},this.sendRequest("",t)))},t.prototype.debug=function(t){var e;null!==(e=this.options)&&void 0!==e&&e.debug&&console.log("[Swetrix]",t)},t.prototype.canTrack=function(){var t,e;return null!==(t=this.options)&&void 0!==t&&t.disabled?(this.debug("Tracking disabled: the 'disabled' setting is set to true."),!1):"undefined"==typeof window?(this.debug("Tracking disabled: script does not run in browser environment."),!1):null!==(t=this.options)&&void 0!==t&&t.respectDNT&&"1"===(null===(e=window.navigator)||void 0===e?void 0:e.doNotTrack)?(this.debug("Tracking disabled: respecting user's 'Do Not Track' preference."),!1):!!(null!==(e=this.options)&&void 0!==e&&e.debug||"localhost"!==(null===location||void 0===location?void 0:location.hostname)&&"127.0.0.1"!==(null===location||void 0===location?void 0:location.hostname)&&""!==(null===location||void 0===location?void 0:location.hostname))&&(null===navigator||void 0===navigator||!navigator.webdriver||(this.debug("Tracking disabled: navigation is automated by WebDriver."),!1))},t.prototype.sendRequest=function(t,e){var i=(null===(n=this.options)||void 0===n?void 0:n.apiURL)||"https://api.swetrix.com/log",n=new XMLHttpRequest;n.open("POST","".concat(i,"/").concat(t),!0),n.setRequestHeader("Content-Type","application/json"),n.send(JSON.stringify(e))},t);function t(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this)}i.LIB_INSTANCE=null,i.init=function(t,e){return i.LIB_INSTANCE||(i.LIB_INSTANCE=new c(t,e)),i.LIB_INSTANCE},i.track=function(t){i.LIB_INSTANCE&&i.LIB_INSTANCE.track(t)},i.trackViews=function(t){i.LIB_INSTANCE&&i.LIB_INSTANCE.trackPageViews(t)},Object.defineProperty(i,"__esModule",{value:!0})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swetrix",
3
- "version": "1.0.3",
3
+ "version": "1.3.1",
4
4
  "description": "The JavaScript analytics client for Swetrix Analytics",
5
5
  "main": "dist/swetrix.cjs.js",
6
6
  "module": "dist/swetrix.es5.js",
@@ -18,24 +18,24 @@
18
18
  "type": "git",
19
19
  "url": "git+https://github.com/Swetrix/swetrix-js.git"
20
20
  },
21
- "author": "Swetrix <contact@swetrix.com>",
22
- "license": "Apache-2.0",
21
+ "author": "Andrii R. <contact@swetrix.com>",
22
+ "license": "MIT",
23
23
  "bugs": {
24
24
  "url": "https://github.com/Swetrix/swetrix-js/issues"
25
25
  },
26
26
  "homepage": "https://swetrix.com/docs",
27
27
  "dependencies": {
28
- "@types/node": "^14.14.41"
28
+ "@types/node": "^14.18.0"
29
29
  },
30
30
  "devDependencies": {
31
+ "@rollup/plugin-commonjs": "^21.0.1",
32
+ "@rollup/plugin-node-resolve": "^13.0.6",
31
33
  "rimraf": "^3.0.2",
32
- "rollup": "^2.53.0",
33
- "rollup-plugin-commonjs": "^10.1.0",
34
- "rollup-plugin-json": "^4.0.0",
34
+ "rollup": "^2.61.1",
35
35
  "rollup-plugin-node-resolve": "^5.2.0",
36
36
  "rollup-plugin-sourcemaps": "^0.6.3",
37
37
  "rollup-plugin-typescript2": "^0.30.0",
38
38
  "rollup-plugin-uglify": "^6.0.4",
39
- "typescript": "^4.3.5"
39
+ "typescript": "^4.5.3"
40
40
  }
41
41
  }
package/rollup.config.js CHANGED
@@ -1,5 +1,5 @@
1
- import resolve from 'rollup-plugin-node-resolve'
2
- import commonjs from 'rollup-plugin-commonjs'
1
+ import { nodeResolve } from '@rollup/plugin-node-resolve'
2
+ import commonjs from '@rollup/plugin-commonjs'
3
3
  import sourceMaps from 'rollup-plugin-sourcemaps'
4
4
  import typescript from 'rollup-plugin-typescript2'
5
5
  import { uglify } from 'rollup-plugin-uglify'
@@ -13,7 +13,7 @@ export default [
13
13
  { file: pkg.module, format: 'es' },
14
14
  ],
15
15
  plugins: [
16
- typescript(), resolve(), commonjs(), sourceMaps(),
16
+ typescript(), nodeResolve(), commonjs(), sourceMaps(),
17
17
  ]
18
18
  },
19
19
  {
@@ -22,7 +22,7 @@ export default [
22
22
  { file: pkg.browser, format: 'umd', name: 'swetrix' },
23
23
  ],
24
24
  plugins: [
25
- typescript(), resolve(), commonjs(), uglify(),
25
+ typescript(), nodeResolve(), commonjs(), uglify(),
26
26
  ]
27
27
  }
28
28
  ]
package/src/Lib.ts CHANGED
@@ -15,6 +15,9 @@ export interface LibOptions {
15
15
  // By setting this flag to `true`, we will not collect ANY kind of data about the user
16
16
  // with the DNT setting.
17
17
  respectDNT?: boolean
18
+
19
+ // Set a custom URL of the API server (for selfhosted variants of Swetrix)
20
+ apiURL?: string
18
21
  }
19
22
 
20
23
  export interface TrackEventOptions {
@@ -37,19 +40,29 @@ export interface PageViewsOptions {
37
40
  // If true, only unique events will be saved
38
41
  // This param is useful when tracking single-page landing websites
39
42
  unique?: boolean
43
+
44
+ // A list of Regular Expressions or string pathes to ignore
45
+ ignore?: Array<any>
46
+
47
+ // Do not send Heartbeat requests to the server
48
+ noHeartbeat?: boolean
49
+
50
+ // Send Heartbeat requests when the website tab is not active in the browser
51
+ heartbeatOnBackground?: boolean
40
52
  }
41
53
 
42
- const host = 'https://api.swetrix.com/log'
54
+ const DEFAULT_API_HOST = 'https://api.swetrix.com/log'
43
55
 
44
56
  export class Lib {
45
57
  private pageData: PageData | null = null
58
+ private pageViewsOptions: PageViewsOptions | null | undefined = null
46
59
 
47
60
  constructor(private projectID: string, private options?: LibOptions) {
48
61
  this.trackPathChange = this.trackPathChange.bind(this)
62
+ this.heartbeat = this.heartbeat.bind(this)
49
63
  }
50
64
 
51
- // Tracks a custom event
52
- track(event: TrackEventOptions) {
65
+ track(event: TrackEventOptions): void {
53
66
  if (!this.canTrack()) {
54
67
  return
55
68
  }
@@ -58,29 +71,38 @@ export class Lib {
58
71
  pid: this.projectID,
59
72
  ...event,
60
73
  }
61
- this.submitCustom(data)
74
+ this.sendRequest('custom', data)
62
75
  }
63
76
 
64
- // Tracks page views
65
- trackPageViews(options?: PageViewsOptions) {
77
+ trackPageViews(options?: PageViewsOptions): void | object {
66
78
  if (!this.canTrack()) {
67
79
  return
68
80
  }
81
+
69
82
  if (this.pageData) {
70
83
  return this.pageData.actions
71
84
  }
72
85
 
73
- let interval: NodeJS.Timeout
86
+ this.pageViewsOptions = options
87
+ let hbInterval: NodeJS.Timeout, interval: NodeJS.Timeout
74
88
  if (!options?.unique) {
75
89
  interval = setInterval(this.trackPathChange, 2000)
76
90
  }
77
91
 
92
+ if (!options?.noHeartbeat) {
93
+ setTimeout(this.heartbeat, 3000)
94
+ hbInterval = setInterval(this.heartbeat, 28000)
95
+ }
96
+
78
97
  const path = getPath()
79
98
 
80
99
  this.pageData = {
81
100
  path,
82
101
  actions: {
83
- stop: options?.unique ? () => { } : () => clearInterval(interval),
102
+ stop: () => {
103
+ clearInterval(interval)
104
+ clearInterval(hbInterval)
105
+ },
84
106
  },
85
107
  }
86
108
 
@@ -88,8 +110,32 @@ export class Lib {
88
110
  return this.pageData.actions
89
111
  }
90
112
 
113
+ private heartbeat(): void {
114
+ if (!this.pageViewsOptions?.heartbeatOnBackground && document.visibilityState === 'hidden') {
115
+ return
116
+ }
117
+
118
+ const data = {
119
+ pid: this.projectID,
120
+ }
121
+
122
+ this.sendRequest('hb', data)
123
+ }
124
+
125
+ private checkIgnore(path: string): boolean {
126
+ const ignore = this.pageViewsOptions?.ignore
127
+
128
+ if (Array.isArray(ignore)) {
129
+ for (let i = 0; i < ignore.length; ++i) {
130
+ if (ignore[i] === path) return true
131
+ if (ignore[i] instanceof RegExp && ignore[i].test(path)) return true
132
+ }
133
+ }
134
+ return false
135
+ }
136
+
91
137
  // Tracking path changes. If path changes -> calling this.trackPage method
92
- private trackPathChange() {
138
+ private trackPathChange(): void {
93
139
  if (!this.pageData) return
94
140
  const newPath = getPath()
95
141
  const { path } = this.pageData
@@ -99,10 +145,12 @@ export class Lib {
99
145
  }
100
146
  }
101
147
 
102
- private trackPage(pg: string, unique: boolean = false) {
148
+ private trackPage(pg: string, unique: boolean = false): void {
103
149
  if (!this.pageData) return
104
150
  this.pageData.path = pg
105
151
 
152
+ if (this.checkIgnore(pg)) return
153
+
106
154
  const data = {
107
155
  pid: this.projectID,
108
156
  lc: getLocale(),
@@ -115,16 +163,21 @@ export class Lib {
115
163
  pg,
116
164
  }
117
165
 
118
- this.submitData(data)
166
+ this.sendRequest('', data)
119
167
  }
120
168
 
121
- private debug(message: string) {
169
+ private debug(message: string): void {
122
170
  if (this.options?.debug) {
123
171
  console.log('[Swetrix]', message)
124
172
  }
125
173
  }
126
174
 
127
- private canTrack() {
175
+ private canTrack(): boolean {
176
+ if (this.options?.disabled) {
177
+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.')
178
+ return false
179
+ }
180
+
128
181
  if (!isInBrowser()) {
129
182
  this.debug('Tracking disabled: script does not run in browser environment.')
130
183
  return false
@@ -147,25 +200,11 @@ export class Lib {
147
200
  return true
148
201
  }
149
202
 
150
- private submitData(body: object) {
151
- return fetch(host, {
152
- method: 'post',
153
- headers: {
154
- 'Accept': 'application/json',
155
- 'Content-Type': 'application/json',
156
- },
157
- body: JSON.stringify(body),
158
- })
159
- }
160
-
161
- private submitCustom(body: object) {
162
- return fetch(`${host}/custom`, {
163
- method: 'post',
164
- headers: {
165
- 'Accept': 'application/json',
166
- 'Content-Type': 'application/json',
167
- },
168
- body: JSON.stringify(body),
169
- })
203
+ private sendRequest(path: string, body: object): void {
204
+ const host = this.options?.apiURL || DEFAULT_API_HOST
205
+ const req = new XMLHttpRequest()
206
+ req.open('POST', `${host}/${path}`, true)
207
+ req.setRequestHeader('Content-Type', 'application/json')
208
+ req.send(JSON.stringify(body))
170
209
  }
171
210
  }