@fle-sdk/event-tracking-web 1.2.0 → 1.2.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/README.md +148 -1
- package/lib/index.esm.js +92 -23
- package/lib/index.esm.min.js +1 -1
- package/lib/index.js +92 -23
- package/lib/index.min.js +1 -1
- package/lib/types/index.d.ts +15 -3
- package/lib/types/type.d.ts +9 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
> **构建用户数据体系,让用户行为数据发挥深远的价值。**
|
|
2
2
|
|
|
3
|
+
**当前版本**: v1.2.0
|
|
4
|
+
|
|
3
5
|
## 前言
|
|
4
6
|
|
|
5
7
|
**WEB 数据埋点 sdk,开始之前请确保了解埋点的架构和基础知识**
|
|
@@ -176,7 +178,10 @@ WebTracking
|
|
|
176
178
|
- track() ---自定义代码埋点上报
|
|
177
179
|
- getDeviceId() ---获取设备唯一标识
|
|
178
180
|
- resetDeviceId() ---重置设备唯一标识
|
|
181
|
+
- setPageKey() ---设置自定义页面唯一标识
|
|
182
|
+
- getPageKey() ---获取当前页面唯一标识
|
|
179
183
|
- clearBatchTimer() ---清理批量发送定时器
|
|
184
|
+
- clearBatchQueue() ---清空批量队列(包括 LocalStorage 中的数据)
|
|
180
185
|
|
|
181
186
|
### Init
|
|
182
187
|
|
|
@@ -199,6 +204,7 @@ WebTracking
|
|
|
199
204
|
| batchSend | boolean | 是否启用批量发送 | 否 | false |
|
|
200
205
|
| batchInterval | number | 批量发送间隔时间(ms) | 否 | 5000 |
|
|
201
206
|
| batchMaxSize | number | 批量发送最大数量 | 否 | 10 |
|
|
207
|
+
| pageKey | string | 自定义页面唯一标识,如果不传则自动从路由获取 | 否 | 自动生成 |
|
|
202
208
|
|
|
203
209
|
#### 例子
|
|
204
210
|
|
|
@@ -228,6 +234,8 @@ const App = () => {
|
|
|
228
234
|
batchSend: true,
|
|
229
235
|
batchInterval: 5000,
|
|
230
236
|
batchMaxSize: 10,
|
|
237
|
+
// 自定义页面标识(可选)
|
|
238
|
+
pageKey: "custom_page_key",
|
|
231
239
|
});
|
|
232
240
|
}, []);
|
|
233
241
|
|
|
@@ -258,6 +266,7 @@ export default App;
|
|
|
258
266
|
| batchSend | boolean | 是否启用批量发送 | 否 | false |
|
|
259
267
|
| batchInterval | number | 批量发送间隔时间(ms) | 否 | 5000 |
|
|
260
268
|
| batchMaxSize | number | 批量发送最大数量 | 否 | 10 |
|
|
269
|
+
| pageKey | string | 自定义页面唯一标识,如果不传则自动从路由获取 | 否 | 自动生成 |
|
|
261
270
|
|
|
262
271
|
#### 例子
|
|
263
272
|
|
|
@@ -286,6 +295,8 @@ const App = () => {
|
|
|
286
295
|
batchMaxSize: 10,
|
|
287
296
|
// 设置采样率为 90%
|
|
288
297
|
sampleRate: 0.9,
|
|
298
|
+
// 自定义页面标识(可选)
|
|
299
|
+
pageKey: "home_page",
|
|
289
300
|
});
|
|
290
301
|
}, []);
|
|
291
302
|
|
|
@@ -423,6 +434,110 @@ const Test = () => {
|
|
|
423
434
|
export default Test;
|
|
424
435
|
```
|
|
425
436
|
|
|
437
|
+
### ClearBatchQueue
|
|
438
|
+
|
|
439
|
+
#### 描述
|
|
440
|
+
|
|
441
|
+
> 清空批量队列。清除内存中的队列数据和 LocalStorage 中持久化的队列数据。适用于需要重置批量发送队列的场景。
|
|
442
|
+
|
|
443
|
+
#### 例子
|
|
444
|
+
|
|
445
|
+
```jsx
|
|
446
|
+
import React from "react";
|
|
447
|
+
import WebTracking from "@fle-sdk/event-tracking-web";
|
|
448
|
+
|
|
449
|
+
const Test = () => {
|
|
450
|
+
const handleClearQueue = () => {
|
|
451
|
+
// 清空批量队列(包括 LocalStorage 中的数据)
|
|
452
|
+
WebTracking.clearBatchQueue();
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
return (
|
|
456
|
+
<div className="Test">
|
|
457
|
+
<button onClick={handleClearQueue}>清空队列</button>
|
|
458
|
+
</div>
|
|
459
|
+
);
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
export default Test;
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
### SetPageKey
|
|
466
|
+
|
|
467
|
+
#### 描述
|
|
468
|
+
|
|
469
|
+
> 设置自定义页面唯一标识。设置后,路由变化时不会自动更新 pageKey(除非设置 `autoUpdate: true`)。
|
|
470
|
+
|
|
471
|
+
#### 参数
|
|
472
|
+
|
|
473
|
+
| 参数名 | type | 描述 | 是否必填 | 默认值 |
|
|
474
|
+
| --------- | -------------- | ------------------------------------------------------------ | -------- | ------ |
|
|
475
|
+
| pageKey | string \| null | 页面唯一标识,如果传入 null 或空字符串,则恢复自动生成 | 是 | - |
|
|
476
|
+
| autoUpdate | boolean | 路由变化时是否自动更新(默认:false,使用自定义值后不再自动更新) | 否 | false |
|
|
477
|
+
|
|
478
|
+
#### 例子
|
|
479
|
+
|
|
480
|
+
```jsx
|
|
481
|
+
import React from "react";
|
|
482
|
+
import WebTracking from "@fle-sdk/event-tracking-web";
|
|
483
|
+
|
|
484
|
+
const Test = () => {
|
|
485
|
+
// 设置自定义页面标识
|
|
486
|
+
const handleSetPageKey = () => {
|
|
487
|
+
WebTracking.setPageKey("custom_page_001");
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
// 设置自定义页面标识,并允许路由变化时自动更新
|
|
491
|
+
const handleSetPageKeyWithAutoUpdate = () => {
|
|
492
|
+
WebTracking.setPageKey("custom_page_001", true);
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
// 恢复自动生成页面标识
|
|
496
|
+
const handleResetPageKey = () => {
|
|
497
|
+
WebTracking.setPageKey(null);
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
return (
|
|
501
|
+
<div className="Test">
|
|
502
|
+
<button onClick={handleSetPageKey}>设置自定义页面标识</button>
|
|
503
|
+
<button onClick={handleSetPageKeyWithAutoUpdate}>设置并允许自动更新</button>
|
|
504
|
+
<button onClick={handleResetPageKey}>恢复自动生成</button>
|
|
505
|
+
</div>
|
|
506
|
+
);
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
export default Test;
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
### GetPageKey
|
|
513
|
+
|
|
514
|
+
#### 描述
|
|
515
|
+
|
|
516
|
+
> 获取当前页面唯一标识。
|
|
517
|
+
|
|
518
|
+
#### 返回值
|
|
519
|
+
|
|
520
|
+
- `string` - 当前页面唯一标识
|
|
521
|
+
|
|
522
|
+
#### 例子
|
|
523
|
+
|
|
524
|
+
```jsx
|
|
525
|
+
import React, { useEffect } from "react";
|
|
526
|
+
import WebTracking from "@fle-sdk/event-tracking-web";
|
|
527
|
+
|
|
528
|
+
const Test = () => {
|
|
529
|
+
useEffect(() => {
|
|
530
|
+
// 获取当前页面标识
|
|
531
|
+
const pageKey = WebTracking.getPageKey();
|
|
532
|
+
console.log("当前页面标识:", pageKey);
|
|
533
|
+
}, []);
|
|
534
|
+
|
|
535
|
+
return <div className="Test"></div>;
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
export default Test;
|
|
539
|
+
```
|
|
540
|
+
|
|
426
541
|
### Track
|
|
427
542
|
|
|
428
543
|
> 手动代码埋点上报
|
|
@@ -568,6 +683,8 @@ const newDeviceId = WebTracking.resetDeviceId();
|
|
|
568
683
|
2. 当队列达到 `batchMaxSize` 时,立即批量发送
|
|
569
684
|
3. 或者每隔 `batchInterval` 毫秒自动发送一次
|
|
570
685
|
4. 批量发送失败时,数据会自动重新加入队列,避免数据丢失
|
|
686
|
+
5. **数据持久化**:队列数据会自动保存到 LocalStorage,页面刷新或关闭后数据不会丢失
|
|
687
|
+
6. **自动恢复**:重新打开页面时,会自动从 LocalStorage 恢复未发送的数据并继续发送
|
|
571
688
|
|
|
572
689
|
#### 使用示例
|
|
573
690
|
|
|
@@ -582,6 +699,14 @@ WebTracking.init({
|
|
|
582
699
|
});
|
|
583
700
|
```
|
|
584
701
|
|
|
702
|
+
#### 数据持久化说明
|
|
703
|
+
|
|
704
|
+
- **自动保存**:每次添加数据到队列时,会自动保存到 LocalStorage
|
|
705
|
+
- **自动恢复**:初始化时(如果启用了批量发送),会自动从 LocalStorage 恢复未发送的数据
|
|
706
|
+
- **页面卸载保护**:页面关闭或刷新时,会自动保存队列数据,确保数据不丢失
|
|
707
|
+
- **存储限制**:如果队列数据超过 4MB,会自动截断保留最新的 80% 数据
|
|
708
|
+
- **存储位置**:LocalStorage key 为 `web_tracking_batch_queue`
|
|
709
|
+
|
|
585
710
|
### 5.3 数据采样
|
|
586
711
|
|
|
587
712
|
当数据量过大时,可以使用数据采样功能来控制上报的数据量,节省服务器资源。
|
|
@@ -627,11 +752,33 @@ SDK 会自动过滤敏感字段,保护用户隐私。默认会过滤以下字
|
|
|
627
752
|
### v1.2.0 (最新)
|
|
628
753
|
|
|
629
754
|
- ✨ 新增设备 ID 管理功能(基于浏览器指纹技术)
|
|
755
|
+
- `getDeviceId()` - 获取设备唯一标识
|
|
756
|
+
- `resetDeviceId()` - 重置设备唯一标识
|
|
757
|
+
- ✨ 新增页面标识自定义功能
|
|
758
|
+
- `pageKey` - 支持在 init 和 preset 中自定义页面标识
|
|
759
|
+
- `setPageKey()` - 动态设置页面标识
|
|
760
|
+
- `getPageKey()` - 获取当前页面标识
|
|
761
|
+
- 支持恢复自动生成模式
|
|
630
762
|
- ✨ 新增批量发送功能,支持批量上报埋点数据
|
|
763
|
+
- `batchSend` - 启用批量发送
|
|
764
|
+
- `batchInterval` - 批量发送间隔时间
|
|
765
|
+
- `batchMaxSize` - 批量发送最大数量
|
|
766
|
+
- **LocalStorage 持久化**:队列数据自动保存,页面刷新不丢失
|
|
767
|
+
- **自动恢复**:重新打开页面时自动恢复未发送的数据
|
|
768
|
+
- `clearBatchQueue()` - 清空批量队列
|
|
631
769
|
- ✨ 新增数据采样功能,支持按比例采样上报
|
|
770
|
+
- `sampleRate` - 数据采样率(0-1之间)
|
|
632
771
|
- ✨ 新增敏感数据自动过滤功能
|
|
772
|
+
- 自动过滤 password、token、secret、key 等敏感字段
|
|
633
773
|
- 🔧 优化类型系统,提升类型安全性
|
|
634
|
-
-
|
|
774
|
+
- 完善 TypeScript 类型定义
|
|
775
|
+
- 新增工具类型和接口
|
|
776
|
+
- 🔧 优化错误处理机制
|
|
777
|
+
- 批量发送失败时自动重试
|
|
778
|
+
- 添加队列大小限制,防止内存溢出
|
|
779
|
+
- 🔧 优化页面卸载处理
|
|
780
|
+
- 使用 `visibilitychange` 和 `beforeunload` 事件保护数据
|
|
781
|
+
- 支持 `sendBeacon` API 优先发送
|
|
635
782
|
- 📝 完善文档和代码注释
|
|
636
783
|
|
|
637
784
|
### v1.1.0
|
package/lib/index.esm.js
CHANGED
|
@@ -1246,7 +1246,9 @@ function (_super) {
|
|
|
1246
1246
|
|
|
1247
1247
|
_this.batchTimer = null; // LocalStorage 存储 key
|
|
1248
1248
|
|
|
1249
|
-
_this.BATCH_QUEUE_STORAGE_KEY =
|
|
1249
|
+
_this.BATCH_QUEUE_STORAGE_KEY = "web_tracking_batch_queue"; // 是否使用自定义 pageKey(如果为 true,路由变化时不会自动更新 pageKey)
|
|
1250
|
+
|
|
1251
|
+
_this.useCustomPageKey = false; // 用户信息
|
|
1250
1252
|
|
|
1251
1253
|
_this.userInfo = null; // 当前路由
|
|
1252
1254
|
|
|
@@ -1271,8 +1273,16 @@ function (_super) {
|
|
|
1271
1273
|
_this.preset(initParams);
|
|
1272
1274
|
|
|
1273
1275
|
var pathname = window.location.pathname;
|
|
1274
|
-
_this.currentUrl = window.location.href;
|
|
1275
|
-
|
|
1276
|
+
_this.currentUrl = window.location.href; // 如果传入了自定义 pageKey,使用自定义值,否则自动生成
|
|
1277
|
+
|
|
1278
|
+
if (initParams.pageKey) {
|
|
1279
|
+
_this.pageKey = initParams.pageKey;
|
|
1280
|
+
_this.useCustomPageKey = true;
|
|
1281
|
+
} else {
|
|
1282
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1283
|
+
_this.useCustomPageKey = false;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1276
1286
|
_this.systemsInfo = _this.getSystemsInfo(initParams.platform); // 获取设备ID
|
|
1277
1287
|
|
|
1278
1288
|
_this.deviceId = _this.getDeviceId();
|
|
@@ -1296,7 +1306,23 @@ function (_super) {
|
|
|
1296
1306
|
|
|
1297
1307
|
_this.preset = function (presetParams) {
|
|
1298
1308
|
if (presetParams instanceof Object) {
|
|
1309
|
+
// 处理 pageKey 特殊逻辑
|
|
1310
|
+
if (presetParams.pageKey !== undefined) {
|
|
1311
|
+
if (presetParams.pageKey === null || presetParams.pageKey === '') {
|
|
1312
|
+
// 恢复自动生成
|
|
1313
|
+
_this.useCustomPageKey = false;
|
|
1314
|
+
var pathname = window.location.pathname;
|
|
1315
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1316
|
+
} else {
|
|
1317
|
+
_this.pageKey = presetParams.pageKey;
|
|
1318
|
+
_this.useCustomPageKey = true;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1299
1322
|
_this.each(presetParams, function (val, key) {
|
|
1323
|
+
// 跳过 pageKey,因为已经单独处理
|
|
1324
|
+
if (key === 'pageKey') return;
|
|
1325
|
+
|
|
1300
1326
|
if (_this.initConfig.hasOwnProperty(key)) {
|
|
1301
1327
|
// TODO:后面加一些校验
|
|
1302
1328
|
_this.initConfig[key] = val;
|
|
@@ -1340,7 +1366,7 @@ function (_super) {
|
|
|
1340
1366
|
} // 获取已存储的设备ID
|
|
1341
1367
|
|
|
1342
1368
|
|
|
1343
|
-
var storedDeviceId = _this.getCookie(
|
|
1369
|
+
var storedDeviceId = _this.getCookie("device_id") || _this.getLocalStorage("device_id");
|
|
1344
1370
|
|
|
1345
1371
|
if (storedDeviceId) {
|
|
1346
1372
|
_this.deviceId = storedDeviceId;
|
|
@@ -1354,10 +1380,10 @@ function (_super) {
|
|
|
1354
1380
|
var deviceId = _this.hashFingerprint(fingerprint); // 存储设备ID(统一使用2年过期时间,与tools.ts保持一致)
|
|
1355
1381
|
|
|
1356
1382
|
|
|
1357
|
-
_this.setCookie(
|
|
1383
|
+
_this.setCookie("device_id", deviceId, 365 * 2); // 存储2年
|
|
1358
1384
|
|
|
1359
1385
|
|
|
1360
|
-
_this.setLocalStorage(
|
|
1386
|
+
_this.setLocalStorage("device_id", deviceId);
|
|
1361
1387
|
|
|
1362
1388
|
_this.deviceId = deviceId;
|
|
1363
1389
|
return _this.deviceId;
|
|
@@ -1371,10 +1397,10 @@ function (_super) {
|
|
|
1371
1397
|
|
|
1372
1398
|
_this.resetDeviceId = function () {
|
|
1373
1399
|
// 清除cookie和localStorage中的设备ID
|
|
1374
|
-
document.cookie =
|
|
1375
|
-
localStorage.removeItem(
|
|
1400
|
+
document.cookie = "device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
|
|
1401
|
+
localStorage.removeItem("device_id"); // 清除内存中的设备ID
|
|
1376
1402
|
|
|
1377
|
-
_this.deviceId =
|
|
1403
|
+
_this.deviceId = ""; // 重新生成设备ID
|
|
1378
1404
|
|
|
1379
1405
|
var newDeviceId = _this.getDeviceId();
|
|
1380
1406
|
|
|
@@ -1389,6 +1415,7 @@ function (_super) {
|
|
|
1389
1415
|
|
|
1390
1416
|
_this.track = function (_a) {
|
|
1391
1417
|
var desc = _a.desc,
|
|
1418
|
+
pageKey = _a.pageKey,
|
|
1392
1419
|
partkey = _a.partkey,
|
|
1393
1420
|
business = _a.business,
|
|
1394
1421
|
header = _a.header;
|
|
@@ -1396,7 +1423,7 @@ function (_super) {
|
|
|
1396
1423
|
var params = _this.getParams({
|
|
1397
1424
|
desc: desc,
|
|
1398
1425
|
event: "CustomTrack",
|
|
1399
|
-
itemKey: _this.getItemKey(partkey),
|
|
1426
|
+
itemKey: _this.getItemKey(partkey, pageKey),
|
|
1400
1427
|
privateParamMap: {
|
|
1401
1428
|
business: business
|
|
1402
1429
|
}
|
|
@@ -1465,12 +1492,51 @@ function (_super) {
|
|
|
1465
1492
|
_this.clearBatchQueue = function () {
|
|
1466
1493
|
_this.batchQueue = [];
|
|
1467
1494
|
|
|
1468
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1495
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1469
1496
|
|
|
1470
1497
|
if (_this.initConfig.showLog) {
|
|
1471
|
-
_this.printLog(
|
|
1498
|
+
_this.printLog("批量队列已清空");
|
|
1472
1499
|
}
|
|
1473
1500
|
};
|
|
1501
|
+
/**
|
|
1502
|
+
* @description 设置自定义页面唯一标识
|
|
1503
|
+
* @param pageKey 页面唯一标识,如果传入 null 或空字符串,则恢复自动生成
|
|
1504
|
+
* @param autoUpdate 路由变化时是否自动更新(默认:false,使用自定义值后不再自动更新)
|
|
1505
|
+
*/
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
_this.setPageKey = function (pageKey, autoUpdate) {
|
|
1509
|
+
if (autoUpdate === void 0) {
|
|
1510
|
+
autoUpdate = false;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
if (pageKey === null || pageKey === '') {
|
|
1514
|
+
// 恢复自动生成
|
|
1515
|
+
_this.useCustomPageKey = false;
|
|
1516
|
+
var pathname = window.location.pathname;
|
|
1517
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1518
|
+
|
|
1519
|
+
if (_this.initConfig.showLog) {
|
|
1520
|
+
_this.printLog("\u9875\u9762\u6807\u8BC6\u5DF2\u6062\u590D\u81EA\u52A8\u751F\u6210: " + _this.pageKey);
|
|
1521
|
+
}
|
|
1522
|
+
} else {
|
|
1523
|
+
_this.pageKey = pageKey;
|
|
1524
|
+
_this.useCustomPageKey = !autoUpdate;
|
|
1525
|
+
|
|
1526
|
+
if (_this.initConfig.showLog) {
|
|
1527
|
+
_this.printLog("\u9875\u9762\u6807\u8BC6\u5DF2\u8BBE\u7F6E\u4E3A: " + pageKey + ", \u81EA\u52A8\u66F4\u65B0: " + autoUpdate);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
/**
|
|
1532
|
+
* @description 获取当前页面唯一标识
|
|
1533
|
+
* @returns 当前页面唯一标识
|
|
1534
|
+
*/
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
_this.getPageKey = function () {
|
|
1538
|
+
return _this.pageKey;
|
|
1539
|
+
};
|
|
1474
1540
|
|
|
1475
1541
|
_this.onClickCallback = function (e) {
|
|
1476
1542
|
var _a;
|
|
@@ -1496,7 +1562,7 @@ function (_super) {
|
|
|
1496
1562
|
targetEle: targetEle,
|
|
1497
1563
|
pointerType: e.pointerType,
|
|
1498
1564
|
currentUrl: _this.currentUrl,
|
|
1499
|
-
elementSelector: _this.getDomSelector(target) ||
|
|
1565
|
+
elementSelector: _this.getDomSelector(target) || ""
|
|
1500
1566
|
}
|
|
1501
1567
|
});
|
|
1502
1568
|
|
|
@@ -1521,8 +1587,11 @@ function (_super) {
|
|
|
1521
1587
|
}
|
|
1522
1588
|
});
|
|
1523
1589
|
|
|
1524
|
-
_this.currentUrl = window.location.href;
|
|
1525
|
-
|
|
1590
|
+
_this.currentUrl = window.location.href; // 如果使用自定义 pageKey,路由变化时不自动更新
|
|
1591
|
+
|
|
1592
|
+
if (!_this.useCustomPageKey) {
|
|
1593
|
+
_this.pageKey = window.location.pathname.replace(/\//g, "_").substring(1);
|
|
1594
|
+
}
|
|
1526
1595
|
|
|
1527
1596
|
_this.sendRetained(e.type);
|
|
1528
1597
|
|
|
@@ -1753,7 +1822,7 @@ function (_super) {
|
|
|
1753
1822
|
_this.printLog("\u6062\u590D\u6279\u91CF\u961F\u5217\u5931\u8D25: " + e); // 如果解析失败,清除损坏的数据
|
|
1754
1823
|
|
|
1755
1824
|
|
|
1756
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1825
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1757
1826
|
}
|
|
1758
1827
|
};
|
|
1759
1828
|
/**
|
|
@@ -1788,13 +1857,13 @@ function (_super) {
|
|
|
1788
1857
|
|
|
1789
1858
|
_this.setupBeforeUnloadListener = function () {
|
|
1790
1859
|
// 使用 visibilitychange 事件(更可靠)
|
|
1791
|
-
document.addEventListener(
|
|
1792
|
-
if (document.visibilityState ===
|
|
1860
|
+
document.addEventListener("visibilitychange", function () {
|
|
1861
|
+
if (document.visibilityState === "hidden" && _this.batchQueue.length > 0) {
|
|
1793
1862
|
_this.saveBatchQueueToStorage();
|
|
1794
1863
|
}
|
|
1795
1864
|
}); // 使用 beforeunload 事件作为备用
|
|
1796
1865
|
|
|
1797
|
-
window.addEventListener(
|
|
1866
|
+
window.addEventListener("beforeunload", function () {
|
|
1798
1867
|
if (_this.batchQueue.length > 0) {
|
|
1799
1868
|
// 使用 sendBeacon 尝试发送数据(如果支持)
|
|
1800
1869
|
if (navigator.sendBeacon && _this.initConfig.serverUrl) {
|
|
@@ -1803,13 +1872,13 @@ function (_super) {
|
|
|
1803
1872
|
events: _this.batchQueue
|
|
1804
1873
|
});
|
|
1805
1874
|
var blob = new Blob([data], {
|
|
1806
|
-
type:
|
|
1875
|
+
type: "application/json"
|
|
1807
1876
|
});
|
|
1808
1877
|
navigator.sendBeacon(_this.initConfig.serverUrl, blob); // 如果 sendBeacon 成功,清除队列
|
|
1809
1878
|
|
|
1810
1879
|
_this.batchQueue = [];
|
|
1811
1880
|
|
|
1812
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1881
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1813
1882
|
} catch (e) {
|
|
1814
1883
|
// sendBeacon 失败,保存到 LocalStorage
|
|
1815
1884
|
_this.saveBatchQueueToStorage();
|
|
@@ -1922,9 +1991,9 @@ function (_super) {
|
|
|
1922
1991
|
*/
|
|
1923
1992
|
|
|
1924
1993
|
|
|
1925
|
-
_this.getItemKey = function (partkey) {
|
|
1994
|
+
_this.getItemKey = function (partkey, pageKey) {
|
|
1926
1995
|
var appKey = _this.initConfig.appKey;
|
|
1927
|
-
var keys = [appKey, _this.pageKey, partkey ? partkey.toString() : undefined].filter(function (key) {
|
|
1996
|
+
var keys = [appKey, (pageKey || _this.pageKey).toString(), partkey ? partkey.toString() : undefined].filter(function (key) {
|
|
1928
1997
|
return !!key;
|
|
1929
1998
|
});
|
|
1930
1999
|
return keys.reduce(function (str, key) {
|
package/lib/index.esm.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(t,n)};var t=function(){return(t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var r=new(function(n){function r(){var e=n.call(this)||this;return e.batchQueue=[],e.batchTimer=null,e.BATCH_QUEUE_STORAGE_KEY="web_tracking_batch_queue",e.userInfo=null,e.currentUrl="",e.pageKey="",e.deviceId="",e.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报"},e.init=function(t){e.preset(t);var n=window.location.pathname;e.currentUrl=window.location.href,e.pageKey=n.replace(/\//g,"_").substring(1),e.systemsInfo=e.getSystemsInfo(t.platform),e.deviceId=e.getDeviceId(),e.setCookie("retainedStartTime",e.getTimeStamp()),e.initConfig.batchSend&&(e.restoreBatchQueueFromStorage(),e.setupBeforeUnloadListener())},e.preset=function(t){t instanceof Object&&e.each(t,(function(t,n){e.initConfig.hasOwnProperty(n)&&(e.initConfig[n]=t)})),/^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-\(\)]*[\w@?^=%&/~+#-\(\)])?$/.test(e.initConfig.serverUrl)||(e.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),e.initConfig.showLog=!0),e.initConfig.autoTrack?e.listener():e.unlistener()},e.login=function(t){e.isObject(t)&&(e.userInfo=t)},e.getDeviceId=function(){if(e.deviceId)return e.deviceId;var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return e.deviceId=t,e.deviceId;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),e.deviceId=r,e.deviceId},e.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),e.deviceId="",e.getDeviceId()},e.track=function(t){var n=t.desc,r=t.partkey,i=t.business,o=t.header,a=e.getParams({desc:n,event:"CustomTrack",itemKey:e.getItemKey(r),privateParamMap:{business:i}});return e.sendData(a,o)},e.listener=function(){e.initConfig.isTrackSinglePage&&(e.rewriteHistory(),e.addSinglePageEvent(e.onPageViewCallback)),e.each(["load","beforeunload"],(function(t){e.addEventListener(window,t,e.onPageViewCallback)})),e.addEventListener(window,"click",e.onClickCallback)},e.unlistener=function(){if(e.initConfig.isTrackSinglePage){var t=window.history.pushState?"popstate":"hashchange";e.each(["pushState","replaceState",t],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)}))}e.each(["load","beforeunload"],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)})),e.removeEventListener(window,"click",e.onClickCallback),e.clearBatchTimer()},e.clearBatchTimer=function(){null!==e.batchTimer&&(clearTimeout(e.batchTimer),e.batchTimer=null)},e.clearBatchQueue=function(){e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]"),e.initConfig.showLog&&e.printLog("批量队列已清空")},e.onClickCallback=function(t){var n,r=t.target;if(null===(n=null==r?void 0:r.dataset)||void 0===n?void 0:n.partKey){var i=[t.pageX,t.pageY],o=r.id,a=r.className,c={id:o,nodeName:r.nodeName,className:a,position:i},s=e.getParams({event:"WebClick",desc:e.eventDescMap.WebClick,itemKey:e.getItemKey(r.dataset.partKey),privateParamMap:{targetEle:c,pointerType:t.pointerType,currentUrl:e.currentUrl,elementSelector:e.getDomSelector(r)||""}});return e.sendData(s)}},e.onPageViewCallback=function(t){var n,r,i=window.location.origin,o=e.getParams({event:"PageView",desc:e.eventDescMap.PageView,privateParamMap:{currentUrl:e.currentUrl,targetUrl:(null===(n=t.arguments)||void 0===n?void 0:n[2])?i+(null===(r=t.arguments)||void 0===r?void 0:r[2]):null}});e.currentUrl=window.location.href,e.pageKey=window.location.pathname.replace(/\//g,"_").substring(1),e.sendRetained(t.type),e.sendData(o)},e.getParams=function(t){var n=t.event,r=t.desc,i=t.privateParamMap,o=void 0===i?{}:i,a=t.itemKey,c=e.initConfig.business,s=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,d=e.filterSensitiveData(c||{}),h=e.filterSensitiveData(e.userInfo||{}),p=e.filterSensitiveData(o||{}),f=e.filterSensitiveData(e.getQueryValue()||{}),v={currentUrl:p.currentUrl||e.currentUrl,business:Object.assign({},d,p.business||{}),pageWidth:s,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:e.sdkVersion,systemsInfo:e.systemsInfo,urlParams:f,userInfo:h,deviceId:e.deviceId};return p.targetEle&&(v.targetEle=p.targetEle),p.targetUrl&&(v.targetUrl=p.targetUrl),p.pointerType&&(v.pointerType=p.pointerType),p.elementSelector&&(v.elementSelector=p.elementSelector),p.retainedDuration&&(v.retainedDuration=p.retainedDuration),{event:n,desc:r,itemKey:a||e.getItemKey(),requestTime:e.getTimeStamp(),privateParamMap:v}},e.shouldSample=function(){var t=e.initConfig.sampleRate;return t>=1||!(t<=0)&&Math.random()<t},e.flushBatchQueue=function(){if(0!==e.batchQueue.length){var t=function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e}([],e.batchQueue);e.batchQueue=[],e.saveBatchQueueToStorage(),e.sendBatchData(t)}},e.sendBatchData=function(t){var n=e.initConfig,r=n.serverUrl,i=n.contentType;n.showLog&&(e.printLog("批量发送 "+t.length+" 条数据"),t.forEach((function(t){return e.printLog(t)}))),e.ajax({url:r,type:"POST",data:JSON.stringify({events:t}),contentType:i,credentials:!1,timeout:e.initConfig.sendTimeout,cors:!0,success:function(){e.initConfig.showLog&&e.printLog("批量发送成功: "+t.length+" 条数据")},error:function(n){var r;e.printLog("批量发送失败: "+n+",数据已重新加入队列"),(r=e.batchQueue).unshift.apply(r,t),e.batchQueue.length>2*e.initConfig.batchMaxSize&&(e.batchQueue=e.batchQueue.slice(0,e.initConfig.batchMaxSize)),e.saveBatchQueueToStorage()}})},e.addToBatchQueue=function(t){var n=e.initConfig,r=n.batchInterval,i=n.batchMaxSize;e.batchQueue.push(t),e.saveBatchQueueToStorage(),e.batchQueue.length>=i?e.flushBatchQueue():e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),r))},e.restoreBatchQueueFromStorage=function(){try{var t=e.getLocalStorage(e.BATCH_QUEUE_STORAGE_KEY);if(t){var n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){e.batchQueue=n,e.initConfig.showLog&&e.printLog("从 LocalStorage 恢复 "+n.length+" 条待发送数据");var r=e.initConfig.batchMaxSize;if(e.batchQueue.length>=r)e.flushBatchQueue();else{var i=e.initConfig.batchInterval;e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),i))}}}}catch(t){e.printLog("恢复批量队列失败: "+t),e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}},e.saveBatchQueueToStorage=function(){try{if(JSON.stringify(e.batchQueue).length>4194304){var t=Math.floor(.8*e.batchQueue.length);e.batchQueue=e.batchQueue.slice(-t),e.printLog("队列过大,已截断保留最新 "+t+" 条数据")}e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,JSON.stringify(e.batchQueue))}catch(t){e.printLog("保存批量队列到 LocalStorage 失败: "+t)}},e.setupBeforeUnloadListener=function(){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e.batchQueue.length>0&&e.saveBatchQueueToStorage()})),window.addEventListener("beforeunload",(function(){if(e.batchQueue.length>0)if(navigator.sendBeacon&&e.initConfig.serverUrl)try{var t=JSON.stringify({events:e.batchQueue}),n=new Blob([t],{type:"application/json"});navigator.sendBeacon(e.initConfig.serverUrl,n),e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}catch(t){e.saveBatchQueueToStorage()}else e.saveBatchQueueToStorage()}))},e.sendData=function(t,n){if(!e.shouldSample())return Promise.resolve({success:!0,message:"数据已采样跳过"});var r=e.initConfig,i=r.serverUrl,o=r.sendTimeout,a=r.contentType,c=r.showLog,s=r.header,u=r.batchSend;return c&&e.printLog(t),u?(e.addToBatchQueue(t),Promise.resolve({success:!0,message:"已添加到批量队列"})):!0!==e.isSupportBeaconSend()||n||s?new Promise((function(r,c){e.ajax({header:n||s,url:i,type:"POST",data:JSON.stringify(t),contentType:a,credentials:!1,timeout:o,cors:!0,success:function(e){return r({success:!0,data:e})},error:function(e,t){return c({success:!1,message:String(e),code:t})}})})):e.sendBeacon({contentType:a,url:i,data:t})},e.sendRetained=function(n){var r=e.getParams({event:"PageRetained",desc:e.eventDescMap.PageRetained});if(["beforeunload","pushState","replaceState","hashchange","popstate"].indexOf(n)>=0){var i=e.getCookie("retainedStartTime"),o=i?+i:e.getTimeStamp(),a=t(t({},r),{privateParamMap:t(t({},r.privateParamMap),{retainedDuration:Math.max(r.requestTime-o,0)})});e.sendData(a),e.setCookie("retainedStartTime",e.getTimeStamp())}},e.getItemKey=function(t){return[e.initConfig.appKey,e.pageKey,t?t.toString():void 0].filter((function(e){return!!e})).reduce((function(e,t){return e+(e.length?".":"")+t}),"")},e.sdkVersion="1.2.0",e.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10},e.systemsInfo={},e}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(r,n),r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(function(){function e(){var e=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",r=[],i={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,c=t.match(/(ipod).*\s([\d_]+)/i),s=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),d=t.match(/(Mac OS X)\s([\d_]+)/i);r=[],l?(r.push("Android "+l[2]),n="h5"):u?(r.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):s?(r.push("iPad, iOS "+s[2].replace(/_/g,".")),n="ipad"):c?(r.push("iPod, iOS "+c[2].replace(/_/g,".")),n="h5"):g?(r.push("Windows "+g[2].replace(/_/g,".")),n="pc"):d&&(r.push("Mac, MacOS "+d[2].replace(/_/g,".")),n="pc"),a&&r.push("WeChat "+a),i.client=r.length?r.join(", "):"Unknown",i.platform=e||n;var h=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return h&&h[0]&&(r=[(h=h[0].split("/"))[1]],i.network=r.length?r.join(", "):"Unknown"),i.ua=t,i},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],r=new Event(e);return function(){var e=n.apply(t,arguments);return r.arguments=arguments,window.dispatchEvent(r),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(t,n,r){if(null==t)return!1;if(e.nativeForEach&&t.forEach===e.nativeForEach)t.forEach(n,r);else if(e.isArray(t)&&t.length===+t.length){for(var i=0,o=t.length;i<o;i++)if(i in t&&n.call(r,t[i],i,t)===e.breaker)return!1}else for(var a in t)if(e.hasOwnProperty.call(t,a)&&n.call(r,t[a],a,t)===e.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,r=e.parentNode.children,i=0;i<r.length;i++)if(r[i].tagName===n){if(e===r[i])return t;t++}return-1},this.selector=function(t){var n=t.parentNode&&9==t.parentNode.nodeType?-1:e.getDomIndex(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(t,n){if(!t||!t.parentNode||!t.parentNode.children)return!1;n=n&&n.join?n:[];var r=t.nodeName.toLowerCase();return t&&"body"!==r&&1==t.nodeType?(n.unshift(e.selector(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?n.join(" > "):e.getDomSelector(t.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return this._decodeURIComponent(i.substring(t.length,i.length))}return null},this.setCookie=function(e,t,n){var r,i="";n=null==n?73e3:n;var o=this.getMainHost();if(r=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),i="; expires="+a.toUTCString()}function c(e){return e||!1}var s="",u="",l="";e&&(s=c(e)),t&&(u=c(t)),r&&(l=c(r)),s&&u&&(document.cookie=s+"="+encodeURIComponent(u)+i+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(t){e.setCookie(t,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var t=e.getCookie("distinctId");return t||(t=e.uuid(),e.setCookie("distinctId",t),t)},this.filterSensitiveData=function(t,n){if(void 0===n&&(n=["password","token","secret","key"]),!e.isObject(t))return t;var r={};return e.each(t,(function(t,i){n.some((function(e){return"string"==typeof i&&i.toLowerCase().includes(e.toLowerCase())}))?r[i]="***":e.isObject(t)?r[i]=e.filterSensitiveData(t,n):r[i]=t})),r},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var r=e[n].replace(/\?|\&/,"").split("=");t[r[0]]=r[1]}return Object.keys(t).length>0?t:null},this.ajax=function(t){function r(e){if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return"object"===n(e)?e:{}}t.timeout=t.timeout||3e4,t.credentials=void 0===t.credentials||t.credentials;var i=e.xhr(t.cors);if(!i)return!1;t.type||(t.type=t.data?"POST":"GET");var o,a=t.success,c=t.error;t.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},t.error=function(e,t){c&&c(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{e.isObject(i)&&i.abort&&i.abort()}catch(t){e.printLog(t)}o&&(clearTimeout(o),o=null,t.error&&t.error(),i.onreadystatechange=null,i.onload=null,i.onerror=null)}()}),t.timeout),i.onreadystatechange=function(){try{4==i.readyState&&(i.status>=200&&i.status<300||304==i.status?t.success&&t.success(r(i.responseText)):t.error&&t.error(r(i.responseText),i.status),i.onreadystatechange=null,i.onload=null)}catch(e){i.onreadystatechange=null,i.onload=null}},i.open(t.type||"GET",t.url,!0);try{t.credentials&&(i.withCredentials=!0),e.isObject(t.header)&&e.each(t.header,(function(e,t){i.setRequestHeader&&i.setRequestHeader(t,e)})),t.data&&(t.cors||i.setRequestHeader&&i.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===t.contentType?i.setRequestHeader&&i.setRequestHeader("Content-type","application/json; charset=UTF-8"):i.setRequestHeader&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(t){e.printLog(t)}i.send(t.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var t=!1;if("object"!==("undefined"==typeof navigator?"undefined":n(navigator))||"function"!=typeof navigator.sendBeacon)return t;var r=e.getUA(),i=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(i.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===r.safari&&(r.safari=Number(o[0])),o[0]&&+o[0]<13?(r.chrome>41||r.firefox>30||r.opera>25||r.safari>12)&&(t=!0):(r.chrome>41||r.firefox>30||r.opera>25||r.safari>11.3)&&(t=!0)}else(r.chrome>38||r.edge>13||r.firefox>30||r.opera>25||r.safari>11)&&(t=!0);return t},this.throttle=function(e,t){var n=null,r=0;return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var a=Date.now(),c=t-(a-r);c<=0||c>t?(n&&(clearTimeout(n),n=null),r=a,e.apply(void 0,i)):n||(n=window.setTimeout((function(){r=Date.now(),n=null,e.apply(void 0,i)}),c))}},this.debounce=function(e,t){var n=null;return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,r)}),t)}},this.sendBeacon=function(t){if(!0===e.isSupportBeaconSend()){var n={type:t.contentType},r=new Blob([JSON.stringify(t.data)],n);return navigator.sendBeacon(t.url,r)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return t;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),r},this.collectFingerprint=function(){var t={};return t.userAgent=navigator.userAgent,t.screenWidth=screen.width,t.screenHeight=screen.height,t.colorDepth=screen.colorDepth,t.pixelDepth=screen.pixelDepth,t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.timezoneOffset=(new Date).getTimezoneOffset(),t.language=navigator.language,t.languages=Array.from(navigator.languages),t.platform=navigator.platform,t.webgl=e.getWebGLFingerprint(),t.canvas=e.getCanvasFingerprint(),t.audio=e.getAudioFingerprint(),t.fonts=e.getFontFingerprint(),t.plugins=e.getPluginsFingerprint(),t.localStorage=e.hasLocalStorage(),t.sessionStorage=e.hasSessionStorage(),t.indexedDB=e.hasIndexedDB(),t.hardwareConcurrency=navigator.hardwareConcurrency,t.deviceMemory=navigator.deviceMemory,t.maxTouchPoints=navigator.maxTouchPoints,t.connection=e.getConnectionFingerprint(),t},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=t.createOscillator(),r=t.createAnalyser(),i=t.createGain(),o=t.createScriptProcessor(4096,1,1);n.type="triangle",n.frequency.value=1e4,i.gain.value=0,n.connect(r),r.connect(o),o.connect(i),i.connect(t.destination),n.start(0);var a=t.sampleRate+"|"+t.currentTime;return n.stop(),t.close(),a}catch(e){return"error"}},this.getFontFingerprint=function(){try{var e=["monospace","sans-serif","serif"],t="mmmmmmmmmmlli",n=document.createElement("canvas").getContext("2d");if(!n)return"not-supported";var r=[],i={};return e.forEach((function(e){n.font="72px "+e,i[e]=n.measureText(t).width})),["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Helvetica","Impact","Times New Roman","Trebuchet MS","Verdana"].forEach((function(o){var a=!1;e.forEach((function(e){n.font="72px '"+o+"', "+e,n.measureText(t).width!==i[e]&&(a=!0)})),a&&r.push(o)})),r.join(",")}catch(e){return"error"}},this.getPluginsFingerprint=function(){try{var e=[];if(navigator.plugins)for(var t=0;t<navigator.plugins.length;t++){var n=navigator.plugins[t];n&&e.push(n.name+"|"+n.description+"|"+n.filename)}return e.join(";")}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.getConnectionFingerprint=function(){try{var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?e.effectiveType+"|"+e.downlink+"|"+e.rtt:"not-supported"}catch(e){return"error"}},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,r=52711,i=0;i<t.length;i++){var o=t.charCodeAt(i);n=(n<<5)+n+o,r=(r<<5)+r+o}return"fp_"+(4096*(n>>>0)+(r>>>0)).toString(36)}}return e.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.isObject(e[0])&&(e[0]=this.formatJsonString(e[0])),"object"===("undefined"==typeof console?"undefined":n(console))&&console.log)try{return console.log.apply(console,e)}catch(t){console.log(e[0])}},e.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},e.prototype.isUndefined=function(e){return void 0===e},e.prototype.isString=function(e){return"[object String]"==toString.call(e)},e.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},e.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},e.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},e.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},e.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},e.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},e.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},e.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),r=document.domain,i=r.split("."),o=[];for(o.unshift(i.pop());i.length;){o.unshift(i.pop());var a=o.join("."),c=e+"=12345;domain=."+a;if(document.cookie=c,t.test(document.cookie))return document.cookie=c+";expires="+n,a}return r},e}()));export default r;
|
|
1
|
+
var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(t,n)};var t=function(){return(t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var r=new(function(n){function r(){var e=n.call(this)||this;return e.batchQueue=[],e.batchTimer=null,e.BATCH_QUEUE_STORAGE_KEY="web_tracking_batch_queue",e.useCustomPageKey=!1,e.userInfo=null,e.currentUrl="",e.pageKey="",e.deviceId="",e.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报"},e.init=function(t){e.preset(t);var n=window.location.pathname;e.currentUrl=window.location.href,t.pageKey?(e.pageKey=t.pageKey,e.useCustomPageKey=!0):(e.pageKey=n.replace(/\//g,"_").substring(1),e.useCustomPageKey=!1),e.systemsInfo=e.getSystemsInfo(t.platform),e.deviceId=e.getDeviceId(),e.setCookie("retainedStartTime",e.getTimeStamp()),e.initConfig.batchSend&&(e.restoreBatchQueueFromStorage(),e.setupBeforeUnloadListener())},e.preset=function(t){if(t instanceof Object){if(void 0!==t.pageKey)if(null===t.pageKey||""===t.pageKey){e.useCustomPageKey=!1;var n=window.location.pathname;e.pageKey=n.replace(/\//g,"_").substring(1)}else e.pageKey=t.pageKey,e.useCustomPageKey=!0;e.each(t,(function(t,n){"pageKey"!==n&&e.initConfig.hasOwnProperty(n)&&(e.initConfig[n]=t)}))}/^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-\(\)]*[\w@?^=%&/~+#-\(\)])?$/.test(e.initConfig.serverUrl)||(e.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),e.initConfig.showLog=!0),e.initConfig.autoTrack?e.listener():e.unlistener()},e.login=function(t){e.isObject(t)&&(e.userInfo=t)},e.getDeviceId=function(){if(e.deviceId)return e.deviceId;var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return e.deviceId=t,e.deviceId;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),e.deviceId=r,e.deviceId},e.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),e.deviceId="",e.getDeviceId()},e.track=function(t){var n=t.desc,r=t.pageKey,i=t.partkey,o=t.business,a=t.header,c=e.getParams({desc:n,event:"CustomTrack",itemKey:e.getItemKey(i,r),privateParamMap:{business:o}});return e.sendData(c,a)},e.listener=function(){e.initConfig.isTrackSinglePage&&(e.rewriteHistory(),e.addSinglePageEvent(e.onPageViewCallback)),e.each(["load","beforeunload"],(function(t){e.addEventListener(window,t,e.onPageViewCallback)})),e.addEventListener(window,"click",e.onClickCallback)},e.unlistener=function(){if(e.initConfig.isTrackSinglePage){var t=window.history.pushState?"popstate":"hashchange";e.each(["pushState","replaceState",t],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)}))}e.each(["load","beforeunload"],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)})),e.removeEventListener(window,"click",e.onClickCallback),e.clearBatchTimer()},e.clearBatchTimer=function(){null!==e.batchTimer&&(clearTimeout(e.batchTimer),e.batchTimer=null)},e.clearBatchQueue=function(){e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]"),e.initConfig.showLog&&e.printLog("批量队列已清空")},e.setPageKey=function(t,n){if(void 0===n&&(n=!1),null===t||""===t){e.useCustomPageKey=!1;var r=window.location.pathname;e.pageKey=r.replace(/\//g,"_").substring(1),e.initConfig.showLog&&e.printLog("页面标识已恢复自动生成: "+e.pageKey)}else e.pageKey=t,e.useCustomPageKey=!n,e.initConfig.showLog&&e.printLog("页面标识已设置为: "+t+", 自动更新: "+n)},e.getPageKey=function(){return e.pageKey},e.onClickCallback=function(t){var n,r=t.target;if(null===(n=null==r?void 0:r.dataset)||void 0===n?void 0:n.partKey){var i=[t.pageX,t.pageY],o=r.id,a=r.className,c={id:o,nodeName:r.nodeName,className:a,position:i},s=e.getParams({event:"WebClick",desc:e.eventDescMap.WebClick,itemKey:e.getItemKey(r.dataset.partKey),privateParamMap:{targetEle:c,pointerType:t.pointerType,currentUrl:e.currentUrl,elementSelector:e.getDomSelector(r)||""}});return e.sendData(s)}},e.onPageViewCallback=function(t){var n,r,i=window.location.origin,o=e.getParams({event:"PageView",desc:e.eventDescMap.PageView,privateParamMap:{currentUrl:e.currentUrl,targetUrl:(null===(n=t.arguments)||void 0===n?void 0:n[2])?i+(null===(r=t.arguments)||void 0===r?void 0:r[2]):null}});e.currentUrl=window.location.href,e.useCustomPageKey||(e.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),e.sendRetained(t.type),e.sendData(o)},e.getParams=function(t){var n=t.event,r=t.desc,i=t.privateParamMap,o=void 0===i?{}:i,a=t.itemKey,c=e.initConfig.business,s=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,d=e.filterSensitiveData(c||{}),p=e.filterSensitiveData(e.userInfo||{}),h=e.filterSensitiveData(o||{}),f=e.filterSensitiveData(e.getQueryValue()||{}),v={currentUrl:h.currentUrl||e.currentUrl,business:Object.assign({},d,h.business||{}),pageWidth:s,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:e.sdkVersion,systemsInfo:e.systemsInfo,urlParams:f,userInfo:p,deviceId:e.deviceId};return h.targetEle&&(v.targetEle=h.targetEle),h.targetUrl&&(v.targetUrl=h.targetUrl),h.pointerType&&(v.pointerType=h.pointerType),h.elementSelector&&(v.elementSelector=h.elementSelector),h.retainedDuration&&(v.retainedDuration=h.retainedDuration),{event:n,desc:r,itemKey:a||e.getItemKey(),requestTime:e.getTimeStamp(),privateParamMap:v}},e.shouldSample=function(){var t=e.initConfig.sampleRate;return t>=1||!(t<=0)&&Math.random()<t},e.flushBatchQueue=function(){if(0!==e.batchQueue.length){var t=function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e}([],e.batchQueue);e.batchQueue=[],e.saveBatchQueueToStorage(),e.sendBatchData(t)}},e.sendBatchData=function(t){var n=e.initConfig,r=n.serverUrl,i=n.contentType;n.showLog&&(e.printLog("批量发送 "+t.length+" 条数据"),t.forEach((function(t){return e.printLog(t)}))),e.ajax({url:r,type:"POST",data:JSON.stringify({events:t}),contentType:i,credentials:!1,timeout:e.initConfig.sendTimeout,cors:!0,success:function(){e.initConfig.showLog&&e.printLog("批量发送成功: "+t.length+" 条数据")},error:function(n){var r;e.printLog("批量发送失败: "+n+",数据已重新加入队列"),(r=e.batchQueue).unshift.apply(r,t),e.batchQueue.length>2*e.initConfig.batchMaxSize&&(e.batchQueue=e.batchQueue.slice(0,e.initConfig.batchMaxSize)),e.saveBatchQueueToStorage()}})},e.addToBatchQueue=function(t){var n=e.initConfig,r=n.batchInterval,i=n.batchMaxSize;e.batchQueue.push(t),e.saveBatchQueueToStorage(),e.batchQueue.length>=i?e.flushBatchQueue():e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),r))},e.restoreBatchQueueFromStorage=function(){try{var t=e.getLocalStorage(e.BATCH_QUEUE_STORAGE_KEY);if(t){var n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){e.batchQueue=n,e.initConfig.showLog&&e.printLog("从 LocalStorage 恢复 "+n.length+" 条待发送数据");var r=e.initConfig.batchMaxSize;if(e.batchQueue.length>=r)e.flushBatchQueue();else{var i=e.initConfig.batchInterval;e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),i))}}}}catch(t){e.printLog("恢复批量队列失败: "+t),e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}},e.saveBatchQueueToStorage=function(){try{if(JSON.stringify(e.batchQueue).length>4194304){var t=Math.floor(.8*e.batchQueue.length);e.batchQueue=e.batchQueue.slice(-t),e.printLog("队列过大,已截断保留最新 "+t+" 条数据")}e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,JSON.stringify(e.batchQueue))}catch(t){e.printLog("保存批量队列到 LocalStorage 失败: "+t)}},e.setupBeforeUnloadListener=function(){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e.batchQueue.length>0&&e.saveBatchQueueToStorage()})),window.addEventListener("beforeunload",(function(){if(e.batchQueue.length>0)if(navigator.sendBeacon&&e.initConfig.serverUrl)try{var t=JSON.stringify({events:e.batchQueue}),n=new Blob([t],{type:"application/json"});navigator.sendBeacon(e.initConfig.serverUrl,n),e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}catch(t){e.saveBatchQueueToStorage()}else e.saveBatchQueueToStorage()}))},e.sendData=function(t,n){if(!e.shouldSample())return Promise.resolve({success:!0,message:"数据已采样跳过"});var r=e.initConfig,i=r.serverUrl,o=r.sendTimeout,a=r.contentType,c=r.showLog,s=r.header,u=r.batchSend;return c&&e.printLog(t),u?(e.addToBatchQueue(t),Promise.resolve({success:!0,message:"已添加到批量队列"})):!0!==e.isSupportBeaconSend()||n||s?new Promise((function(r,c){e.ajax({header:n||s,url:i,type:"POST",data:JSON.stringify(t),contentType:a,credentials:!1,timeout:o,cors:!0,success:function(e){return r({success:!0,data:e})},error:function(e,t){return c({success:!1,message:String(e),code:t})}})})):e.sendBeacon({contentType:a,url:i,data:t})},e.sendRetained=function(n){var r=e.getParams({event:"PageRetained",desc:e.eventDescMap.PageRetained});if(["beforeunload","pushState","replaceState","hashchange","popstate"].indexOf(n)>=0){var i=e.getCookie("retainedStartTime"),o=i?+i:e.getTimeStamp(),a=t(t({},r),{privateParamMap:t(t({},r.privateParamMap),{retainedDuration:Math.max(r.requestTime-o,0)})});e.sendData(a),e.setCookie("retainedStartTime",e.getTimeStamp())}},e.getItemKey=function(t,n){return[e.initConfig.appKey,(n||e.pageKey).toString(),t?t.toString():void 0].filter((function(e){return!!e})).reduce((function(e,t){return e+(e.length?".":"")+t}),"")},e.sdkVersion="1.2.0",e.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10},e.systemsInfo={},e}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(r,n),r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(function(){function e(){var e=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",r=[],i={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,c=t.match(/(ipod).*\s([\d_]+)/i),s=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),d=t.match(/(Mac OS X)\s([\d_]+)/i);r=[],l?(r.push("Android "+l[2]),n="h5"):u?(r.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):s?(r.push("iPad, iOS "+s[2].replace(/_/g,".")),n="ipad"):c?(r.push("iPod, iOS "+c[2].replace(/_/g,".")),n="h5"):g?(r.push("Windows "+g[2].replace(/_/g,".")),n="pc"):d&&(r.push("Mac, MacOS "+d[2].replace(/_/g,".")),n="pc"),a&&r.push("WeChat "+a),i.client=r.length?r.join(", "):"Unknown",i.platform=e||n;var p=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return p&&p[0]&&(r=[(p=p[0].split("/"))[1]],i.network=r.length?r.join(", "):"Unknown"),i.ua=t,i},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],r=new Event(e);return function(){var e=n.apply(t,arguments);return r.arguments=arguments,window.dispatchEvent(r),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(t,n,r){if(null==t)return!1;if(e.nativeForEach&&t.forEach===e.nativeForEach)t.forEach(n,r);else if(e.isArray(t)&&t.length===+t.length){for(var i=0,o=t.length;i<o;i++)if(i in t&&n.call(r,t[i],i,t)===e.breaker)return!1}else for(var a in t)if(e.hasOwnProperty.call(t,a)&&n.call(r,t[a],a,t)===e.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,r=e.parentNode.children,i=0;i<r.length;i++)if(r[i].tagName===n){if(e===r[i])return t;t++}return-1},this.selector=function(t){var n=t.parentNode&&9==t.parentNode.nodeType?-1:e.getDomIndex(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(t,n){if(!t||!t.parentNode||!t.parentNode.children)return!1;n=n&&n.join?n:[];var r=t.nodeName.toLowerCase();return t&&"body"!==r&&1==t.nodeType?(n.unshift(e.selector(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?n.join(" > "):e.getDomSelector(t.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return this._decodeURIComponent(i.substring(t.length,i.length))}return null},this.setCookie=function(e,t,n){var r,i="";n=null==n?73e3:n;var o=this.getMainHost();if(r=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),i="; expires="+a.toUTCString()}function c(e){return e||!1}var s="",u="",l="";e&&(s=c(e)),t&&(u=c(t)),r&&(l=c(r)),s&&u&&(document.cookie=s+"="+encodeURIComponent(u)+i+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(t){e.setCookie(t,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var t=e.getCookie("distinctId");return t||(t=e.uuid(),e.setCookie("distinctId",t),t)},this.filterSensitiveData=function(t,n){if(void 0===n&&(n=["password","token","secret","key"]),!e.isObject(t))return t;var r={};return e.each(t,(function(t,i){n.some((function(e){return"string"==typeof i&&i.toLowerCase().includes(e.toLowerCase())}))?r[i]="***":e.isObject(t)?r[i]=e.filterSensitiveData(t,n):r[i]=t})),r},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var r=e[n].replace(/\?|\&/,"").split("=");t[r[0]]=r[1]}return Object.keys(t).length>0?t:null},this.ajax=function(t){function r(e){if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return"object"===n(e)?e:{}}t.timeout=t.timeout||3e4,t.credentials=void 0===t.credentials||t.credentials;var i=e.xhr(t.cors);if(!i)return!1;t.type||(t.type=t.data?"POST":"GET");var o,a=t.success,c=t.error;t.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},t.error=function(e,t){c&&c(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{e.isObject(i)&&i.abort&&i.abort()}catch(t){e.printLog(t)}o&&(clearTimeout(o),o=null,t.error&&t.error(),i.onreadystatechange=null,i.onload=null,i.onerror=null)}()}),t.timeout),i.onreadystatechange=function(){try{4==i.readyState&&(i.status>=200&&i.status<300||304==i.status?t.success&&t.success(r(i.responseText)):t.error&&t.error(r(i.responseText),i.status),i.onreadystatechange=null,i.onload=null)}catch(e){i.onreadystatechange=null,i.onload=null}},i.open(t.type||"GET",t.url,!0);try{t.credentials&&(i.withCredentials=!0),e.isObject(t.header)&&e.each(t.header,(function(e,t){i.setRequestHeader&&i.setRequestHeader(t,e)})),t.data&&(t.cors||i.setRequestHeader&&i.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===t.contentType?i.setRequestHeader&&i.setRequestHeader("Content-type","application/json; charset=UTF-8"):i.setRequestHeader&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(t){e.printLog(t)}i.send(t.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var t=!1;if("object"!==("undefined"==typeof navigator?"undefined":n(navigator))||"function"!=typeof navigator.sendBeacon)return t;var r=e.getUA(),i=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(i.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===r.safari&&(r.safari=Number(o[0])),o[0]&&+o[0]<13?(r.chrome>41||r.firefox>30||r.opera>25||r.safari>12)&&(t=!0):(r.chrome>41||r.firefox>30||r.opera>25||r.safari>11.3)&&(t=!0)}else(r.chrome>38||r.edge>13||r.firefox>30||r.opera>25||r.safari>11)&&(t=!0);return t},this.throttle=function(e,t){var n=null,r=0;return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var a=Date.now(),c=t-(a-r);c<=0||c>t?(n&&(clearTimeout(n),n=null),r=a,e.apply(void 0,i)):n||(n=window.setTimeout((function(){r=Date.now(),n=null,e.apply(void 0,i)}),c))}},this.debounce=function(e,t){var n=null;return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,r)}),t)}},this.sendBeacon=function(t){if(!0===e.isSupportBeaconSend()){var n={type:t.contentType},r=new Blob([JSON.stringify(t.data)],n);return navigator.sendBeacon(t.url,r)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return t;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),r},this.collectFingerprint=function(){var t={};return t.userAgent=navigator.userAgent,t.screenWidth=screen.width,t.screenHeight=screen.height,t.colorDepth=screen.colorDepth,t.pixelDepth=screen.pixelDepth,t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.timezoneOffset=(new Date).getTimezoneOffset(),t.language=navigator.language,t.languages=Array.from(navigator.languages),t.platform=navigator.platform,t.webgl=e.getWebGLFingerprint(),t.canvas=e.getCanvasFingerprint(),t.audio=e.getAudioFingerprint(),t.fonts=e.getFontFingerprint(),t.plugins=e.getPluginsFingerprint(),t.localStorage=e.hasLocalStorage(),t.sessionStorage=e.hasSessionStorage(),t.indexedDB=e.hasIndexedDB(),t.hardwareConcurrency=navigator.hardwareConcurrency,t.deviceMemory=navigator.deviceMemory,t.maxTouchPoints=navigator.maxTouchPoints,t.connection=e.getConnectionFingerprint(),t},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=t.createOscillator(),r=t.createAnalyser(),i=t.createGain(),o=t.createScriptProcessor(4096,1,1);n.type="triangle",n.frequency.value=1e4,i.gain.value=0,n.connect(r),r.connect(o),o.connect(i),i.connect(t.destination),n.start(0);var a=t.sampleRate+"|"+t.currentTime;return n.stop(),t.close(),a}catch(e){return"error"}},this.getFontFingerprint=function(){try{var e=["monospace","sans-serif","serif"],t="mmmmmmmmmmlli",n=document.createElement("canvas").getContext("2d");if(!n)return"not-supported";var r=[],i={};return e.forEach((function(e){n.font="72px "+e,i[e]=n.measureText(t).width})),["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Helvetica","Impact","Times New Roman","Trebuchet MS","Verdana"].forEach((function(o){var a=!1;e.forEach((function(e){n.font="72px '"+o+"', "+e,n.measureText(t).width!==i[e]&&(a=!0)})),a&&r.push(o)})),r.join(",")}catch(e){return"error"}},this.getPluginsFingerprint=function(){try{var e=[];if(navigator.plugins)for(var t=0;t<navigator.plugins.length;t++){var n=navigator.plugins[t];n&&e.push(n.name+"|"+n.description+"|"+n.filename)}return e.join(";")}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.getConnectionFingerprint=function(){try{var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?e.effectiveType+"|"+e.downlink+"|"+e.rtt:"not-supported"}catch(e){return"error"}},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,r=52711,i=0;i<t.length;i++){var o=t.charCodeAt(i);n=(n<<5)+n+o,r=(r<<5)+r+o}return"fp_"+(4096*(n>>>0)+(r>>>0)).toString(36)}}return e.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.isObject(e[0])&&(e[0]=this.formatJsonString(e[0])),"object"===("undefined"==typeof console?"undefined":n(console))&&console.log)try{return console.log.apply(console,e)}catch(t){console.log(e[0])}},e.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},e.prototype.isUndefined=function(e){return void 0===e},e.prototype.isString=function(e){return"[object String]"==toString.call(e)},e.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},e.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},e.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},e.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},e.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},e.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},e.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},e.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),r=document.domain,i=r.split("."),o=[];for(o.unshift(i.pop());i.length;){o.unshift(i.pop());var a=o.join("."),c=e+"=12345;domain=."+a;if(document.cookie=c,t.test(document.cookie))return document.cookie=c+";expires="+n,a}return r},e}()));export default r;
|
package/lib/index.js
CHANGED
|
@@ -1252,7 +1252,9 @@
|
|
|
1252
1252
|
|
|
1253
1253
|
_this.batchTimer = null; // LocalStorage 存储 key
|
|
1254
1254
|
|
|
1255
|
-
_this.BATCH_QUEUE_STORAGE_KEY =
|
|
1255
|
+
_this.BATCH_QUEUE_STORAGE_KEY = "web_tracking_batch_queue"; // 是否使用自定义 pageKey(如果为 true,路由变化时不会自动更新 pageKey)
|
|
1256
|
+
|
|
1257
|
+
_this.useCustomPageKey = false; // 用户信息
|
|
1256
1258
|
|
|
1257
1259
|
_this.userInfo = null; // 当前路由
|
|
1258
1260
|
|
|
@@ -1277,8 +1279,16 @@
|
|
|
1277
1279
|
_this.preset(initParams);
|
|
1278
1280
|
|
|
1279
1281
|
var pathname = window.location.pathname;
|
|
1280
|
-
_this.currentUrl = window.location.href;
|
|
1281
|
-
|
|
1282
|
+
_this.currentUrl = window.location.href; // 如果传入了自定义 pageKey,使用自定义值,否则自动生成
|
|
1283
|
+
|
|
1284
|
+
if (initParams.pageKey) {
|
|
1285
|
+
_this.pageKey = initParams.pageKey;
|
|
1286
|
+
_this.useCustomPageKey = true;
|
|
1287
|
+
} else {
|
|
1288
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1289
|
+
_this.useCustomPageKey = false;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1282
1292
|
_this.systemsInfo = _this.getSystemsInfo(initParams.platform); // 获取设备ID
|
|
1283
1293
|
|
|
1284
1294
|
_this.deviceId = _this.getDeviceId();
|
|
@@ -1302,7 +1312,23 @@
|
|
|
1302
1312
|
|
|
1303
1313
|
_this.preset = function (presetParams) {
|
|
1304
1314
|
if (presetParams instanceof Object) {
|
|
1315
|
+
// 处理 pageKey 特殊逻辑
|
|
1316
|
+
if (presetParams.pageKey !== undefined) {
|
|
1317
|
+
if (presetParams.pageKey === null || presetParams.pageKey === '') {
|
|
1318
|
+
// 恢复自动生成
|
|
1319
|
+
_this.useCustomPageKey = false;
|
|
1320
|
+
var pathname = window.location.pathname;
|
|
1321
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1322
|
+
} else {
|
|
1323
|
+
_this.pageKey = presetParams.pageKey;
|
|
1324
|
+
_this.useCustomPageKey = true;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1305
1328
|
_this.each(presetParams, function (val, key) {
|
|
1329
|
+
// 跳过 pageKey,因为已经单独处理
|
|
1330
|
+
if (key === 'pageKey') return;
|
|
1331
|
+
|
|
1306
1332
|
if (_this.initConfig.hasOwnProperty(key)) {
|
|
1307
1333
|
// TODO:后面加一些校验
|
|
1308
1334
|
_this.initConfig[key] = val;
|
|
@@ -1346,7 +1372,7 @@
|
|
|
1346
1372
|
} // 获取已存储的设备ID
|
|
1347
1373
|
|
|
1348
1374
|
|
|
1349
|
-
var storedDeviceId = _this.getCookie(
|
|
1375
|
+
var storedDeviceId = _this.getCookie("device_id") || _this.getLocalStorage("device_id");
|
|
1350
1376
|
|
|
1351
1377
|
if (storedDeviceId) {
|
|
1352
1378
|
_this.deviceId = storedDeviceId;
|
|
@@ -1360,10 +1386,10 @@
|
|
|
1360
1386
|
var deviceId = _this.hashFingerprint(fingerprint); // 存储设备ID(统一使用2年过期时间,与tools.ts保持一致)
|
|
1361
1387
|
|
|
1362
1388
|
|
|
1363
|
-
_this.setCookie(
|
|
1389
|
+
_this.setCookie("device_id", deviceId, 365 * 2); // 存储2年
|
|
1364
1390
|
|
|
1365
1391
|
|
|
1366
|
-
_this.setLocalStorage(
|
|
1392
|
+
_this.setLocalStorage("device_id", deviceId);
|
|
1367
1393
|
|
|
1368
1394
|
_this.deviceId = deviceId;
|
|
1369
1395
|
return _this.deviceId;
|
|
@@ -1377,10 +1403,10 @@
|
|
|
1377
1403
|
|
|
1378
1404
|
_this.resetDeviceId = function () {
|
|
1379
1405
|
// 清除cookie和localStorage中的设备ID
|
|
1380
|
-
document.cookie =
|
|
1381
|
-
localStorage.removeItem(
|
|
1406
|
+
document.cookie = "device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
|
|
1407
|
+
localStorage.removeItem("device_id"); // 清除内存中的设备ID
|
|
1382
1408
|
|
|
1383
|
-
_this.deviceId =
|
|
1409
|
+
_this.deviceId = ""; // 重新生成设备ID
|
|
1384
1410
|
|
|
1385
1411
|
var newDeviceId = _this.getDeviceId();
|
|
1386
1412
|
|
|
@@ -1395,6 +1421,7 @@
|
|
|
1395
1421
|
|
|
1396
1422
|
_this.track = function (_a) {
|
|
1397
1423
|
var desc = _a.desc,
|
|
1424
|
+
pageKey = _a.pageKey,
|
|
1398
1425
|
partkey = _a.partkey,
|
|
1399
1426
|
business = _a.business,
|
|
1400
1427
|
header = _a.header;
|
|
@@ -1402,7 +1429,7 @@
|
|
|
1402
1429
|
var params = _this.getParams({
|
|
1403
1430
|
desc: desc,
|
|
1404
1431
|
event: "CustomTrack",
|
|
1405
|
-
itemKey: _this.getItemKey(partkey),
|
|
1432
|
+
itemKey: _this.getItemKey(partkey, pageKey),
|
|
1406
1433
|
privateParamMap: {
|
|
1407
1434
|
business: business
|
|
1408
1435
|
}
|
|
@@ -1471,12 +1498,51 @@
|
|
|
1471
1498
|
_this.clearBatchQueue = function () {
|
|
1472
1499
|
_this.batchQueue = [];
|
|
1473
1500
|
|
|
1474
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1501
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1475
1502
|
|
|
1476
1503
|
if (_this.initConfig.showLog) {
|
|
1477
|
-
_this.printLog(
|
|
1504
|
+
_this.printLog("批量队列已清空");
|
|
1478
1505
|
}
|
|
1479
1506
|
};
|
|
1507
|
+
/**
|
|
1508
|
+
* @description 设置自定义页面唯一标识
|
|
1509
|
+
* @param pageKey 页面唯一标识,如果传入 null 或空字符串,则恢复自动生成
|
|
1510
|
+
* @param autoUpdate 路由变化时是否自动更新(默认:false,使用自定义值后不再自动更新)
|
|
1511
|
+
*/
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
_this.setPageKey = function (pageKey, autoUpdate) {
|
|
1515
|
+
if (autoUpdate === void 0) {
|
|
1516
|
+
autoUpdate = false;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
if (pageKey === null || pageKey === '') {
|
|
1520
|
+
// 恢复自动生成
|
|
1521
|
+
_this.useCustomPageKey = false;
|
|
1522
|
+
var pathname = window.location.pathname;
|
|
1523
|
+
_this.pageKey = pathname.replace(/\//g, "_").substring(1);
|
|
1524
|
+
|
|
1525
|
+
if (_this.initConfig.showLog) {
|
|
1526
|
+
_this.printLog("\u9875\u9762\u6807\u8BC6\u5DF2\u6062\u590D\u81EA\u52A8\u751F\u6210: " + _this.pageKey);
|
|
1527
|
+
}
|
|
1528
|
+
} else {
|
|
1529
|
+
_this.pageKey = pageKey;
|
|
1530
|
+
_this.useCustomPageKey = !autoUpdate;
|
|
1531
|
+
|
|
1532
|
+
if (_this.initConfig.showLog) {
|
|
1533
|
+
_this.printLog("\u9875\u9762\u6807\u8BC6\u5DF2\u8BBE\u7F6E\u4E3A: " + pageKey + ", \u81EA\u52A8\u66F4\u65B0: " + autoUpdate);
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
/**
|
|
1538
|
+
* @description 获取当前页面唯一标识
|
|
1539
|
+
* @returns 当前页面唯一标识
|
|
1540
|
+
*/
|
|
1541
|
+
|
|
1542
|
+
|
|
1543
|
+
_this.getPageKey = function () {
|
|
1544
|
+
return _this.pageKey;
|
|
1545
|
+
};
|
|
1480
1546
|
|
|
1481
1547
|
_this.onClickCallback = function (e) {
|
|
1482
1548
|
var _a;
|
|
@@ -1502,7 +1568,7 @@
|
|
|
1502
1568
|
targetEle: targetEle,
|
|
1503
1569
|
pointerType: e.pointerType,
|
|
1504
1570
|
currentUrl: _this.currentUrl,
|
|
1505
|
-
elementSelector: _this.getDomSelector(target) ||
|
|
1571
|
+
elementSelector: _this.getDomSelector(target) || ""
|
|
1506
1572
|
}
|
|
1507
1573
|
});
|
|
1508
1574
|
|
|
@@ -1527,8 +1593,11 @@
|
|
|
1527
1593
|
}
|
|
1528
1594
|
});
|
|
1529
1595
|
|
|
1530
|
-
_this.currentUrl = window.location.href;
|
|
1531
|
-
|
|
1596
|
+
_this.currentUrl = window.location.href; // 如果使用自定义 pageKey,路由变化时不自动更新
|
|
1597
|
+
|
|
1598
|
+
if (!_this.useCustomPageKey) {
|
|
1599
|
+
_this.pageKey = window.location.pathname.replace(/\//g, "_").substring(1);
|
|
1600
|
+
}
|
|
1532
1601
|
|
|
1533
1602
|
_this.sendRetained(e.type);
|
|
1534
1603
|
|
|
@@ -1759,7 +1828,7 @@
|
|
|
1759
1828
|
_this.printLog("\u6062\u590D\u6279\u91CF\u961F\u5217\u5931\u8D25: " + e); // 如果解析失败,清除损坏的数据
|
|
1760
1829
|
|
|
1761
1830
|
|
|
1762
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1831
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1763
1832
|
}
|
|
1764
1833
|
};
|
|
1765
1834
|
/**
|
|
@@ -1794,13 +1863,13 @@
|
|
|
1794
1863
|
|
|
1795
1864
|
_this.setupBeforeUnloadListener = function () {
|
|
1796
1865
|
// 使用 visibilitychange 事件(更可靠)
|
|
1797
|
-
document.addEventListener(
|
|
1798
|
-
if (document.visibilityState ===
|
|
1866
|
+
document.addEventListener("visibilitychange", function () {
|
|
1867
|
+
if (document.visibilityState === "hidden" && _this.batchQueue.length > 0) {
|
|
1799
1868
|
_this.saveBatchQueueToStorage();
|
|
1800
1869
|
}
|
|
1801
1870
|
}); // 使用 beforeunload 事件作为备用
|
|
1802
1871
|
|
|
1803
|
-
window.addEventListener(
|
|
1872
|
+
window.addEventListener("beforeunload", function () {
|
|
1804
1873
|
if (_this.batchQueue.length > 0) {
|
|
1805
1874
|
// 使用 sendBeacon 尝试发送数据(如果支持)
|
|
1806
1875
|
if (navigator.sendBeacon && _this.initConfig.serverUrl) {
|
|
@@ -1809,13 +1878,13 @@
|
|
|
1809
1878
|
events: _this.batchQueue
|
|
1810
1879
|
});
|
|
1811
1880
|
var blob = new Blob([data], {
|
|
1812
|
-
type:
|
|
1881
|
+
type: "application/json"
|
|
1813
1882
|
});
|
|
1814
1883
|
navigator.sendBeacon(_this.initConfig.serverUrl, blob); // 如果 sendBeacon 成功,清除队列
|
|
1815
1884
|
|
|
1816
1885
|
_this.batchQueue = [];
|
|
1817
1886
|
|
|
1818
|
-
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY,
|
|
1887
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1819
1888
|
} catch (e) {
|
|
1820
1889
|
// sendBeacon 失败,保存到 LocalStorage
|
|
1821
1890
|
_this.saveBatchQueueToStorage();
|
|
@@ -1928,9 +1997,9 @@
|
|
|
1928
1997
|
*/
|
|
1929
1998
|
|
|
1930
1999
|
|
|
1931
|
-
_this.getItemKey = function (partkey) {
|
|
2000
|
+
_this.getItemKey = function (partkey, pageKey) {
|
|
1932
2001
|
var appKey = _this.initConfig.appKey;
|
|
1933
|
-
var keys = [appKey, _this.pageKey, partkey ? partkey.toString() : undefined].filter(function (key) {
|
|
2002
|
+
var keys = [appKey, (pageKey || _this.pageKey).toString(), partkey ? partkey.toString() : undefined].filter(function (key) {
|
|
1934
2003
|
return !!key;
|
|
1935
2004
|
});
|
|
1936
2005
|
return keys.reduce(function (str, key) {
|
package/lib/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).WebTracking=t()}(this,(function(){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(t,n)};var t=function(){return(t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}return new(function(n){function r(){var e=n.call(this)||this;return e.batchQueue=[],e.batchTimer=null,e.BATCH_QUEUE_STORAGE_KEY="web_tracking_batch_queue",e.userInfo=null,e.currentUrl="",e.pageKey="",e.deviceId="",e.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报"},e.init=function(t){e.preset(t);var n=window.location.pathname;e.currentUrl=window.location.href,e.pageKey=n.replace(/\//g,"_").substring(1),e.systemsInfo=e.getSystemsInfo(t.platform),e.deviceId=e.getDeviceId(),e.setCookie("retainedStartTime",e.getTimeStamp()),e.initConfig.batchSend&&(e.restoreBatchQueueFromStorage(),e.setupBeforeUnloadListener())},e.preset=function(t){t instanceof Object&&e.each(t,(function(t,n){e.initConfig.hasOwnProperty(n)&&(e.initConfig[n]=t)})),/^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-\(\)]*[\w@?^=%&/~+#-\(\)])?$/.test(e.initConfig.serverUrl)||(e.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),e.initConfig.showLog=!0),e.initConfig.autoTrack?e.listener():e.unlistener()},e.login=function(t){e.isObject(t)&&(e.userInfo=t)},e.getDeviceId=function(){if(e.deviceId)return e.deviceId;var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return e.deviceId=t,e.deviceId;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),e.deviceId=r,e.deviceId},e.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),e.deviceId="",e.getDeviceId()},e.track=function(t){var n=t.desc,r=t.partkey,i=t.business,o=t.header,a=e.getParams({desc:n,event:"CustomTrack",itemKey:e.getItemKey(r),privateParamMap:{business:i}});return e.sendData(a,o)},e.listener=function(){e.initConfig.isTrackSinglePage&&(e.rewriteHistory(),e.addSinglePageEvent(e.onPageViewCallback)),e.each(["load","beforeunload"],(function(t){e.addEventListener(window,t,e.onPageViewCallback)})),e.addEventListener(window,"click",e.onClickCallback)},e.unlistener=function(){if(e.initConfig.isTrackSinglePage){var t=window.history.pushState?"popstate":"hashchange";e.each(["pushState","replaceState",t],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)}))}e.each(["load","beforeunload"],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)})),e.removeEventListener(window,"click",e.onClickCallback),e.clearBatchTimer()},e.clearBatchTimer=function(){null!==e.batchTimer&&(clearTimeout(e.batchTimer),e.batchTimer=null)},e.clearBatchQueue=function(){e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]"),e.initConfig.showLog&&e.printLog("批量队列已清空")},e.onClickCallback=function(t){var n,r=t.target;if(null===(n=null==r?void 0:r.dataset)||void 0===n?void 0:n.partKey){var i=[t.pageX,t.pageY],o=r.id,a=r.className,c={id:o,nodeName:r.nodeName,className:a,position:i},s=e.getParams({event:"WebClick",desc:e.eventDescMap.WebClick,itemKey:e.getItemKey(r.dataset.partKey),privateParamMap:{targetEle:c,pointerType:t.pointerType,currentUrl:e.currentUrl,elementSelector:e.getDomSelector(r)||""}});return e.sendData(s)}},e.onPageViewCallback=function(t){var n,r,i=window.location.origin,o=e.getParams({event:"PageView",desc:e.eventDescMap.PageView,privateParamMap:{currentUrl:e.currentUrl,targetUrl:(null===(n=t.arguments)||void 0===n?void 0:n[2])?i+(null===(r=t.arguments)||void 0===r?void 0:r[2]):null}});e.currentUrl=window.location.href,e.pageKey=window.location.pathname.replace(/\//g,"_").substring(1),e.sendRetained(t.type),e.sendData(o)},e.getParams=function(t){var n=t.event,r=t.desc,i=t.privateParamMap,o=void 0===i?{}:i,a=t.itemKey,c=e.initConfig.business,s=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,d=e.filterSensitiveData(c||{}),h=e.filterSensitiveData(e.userInfo||{}),p=e.filterSensitiveData(o||{}),f=e.filterSensitiveData(e.getQueryValue()||{}),v={currentUrl:p.currentUrl||e.currentUrl,business:Object.assign({},d,p.business||{}),pageWidth:s,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:e.sdkVersion,systemsInfo:e.systemsInfo,urlParams:f,userInfo:h,deviceId:e.deviceId};return p.targetEle&&(v.targetEle=p.targetEle),p.targetUrl&&(v.targetUrl=p.targetUrl),p.pointerType&&(v.pointerType=p.pointerType),p.elementSelector&&(v.elementSelector=p.elementSelector),p.retainedDuration&&(v.retainedDuration=p.retainedDuration),{event:n,desc:r,itemKey:a||e.getItemKey(),requestTime:e.getTimeStamp(),privateParamMap:v}},e.shouldSample=function(){var t=e.initConfig.sampleRate;return t>=1||!(t<=0)&&Math.random()<t},e.flushBatchQueue=function(){if(0!==e.batchQueue.length){var t=function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e}([],e.batchQueue);e.batchQueue=[],e.saveBatchQueueToStorage(),e.sendBatchData(t)}},e.sendBatchData=function(t){var n=e.initConfig,r=n.serverUrl,i=n.contentType;n.showLog&&(e.printLog("批量发送 "+t.length+" 条数据"),t.forEach((function(t){return e.printLog(t)}))),e.ajax({url:r,type:"POST",data:JSON.stringify({events:t}),contentType:i,credentials:!1,timeout:e.initConfig.sendTimeout,cors:!0,success:function(){e.initConfig.showLog&&e.printLog("批量发送成功: "+t.length+" 条数据")},error:function(n){var r;e.printLog("批量发送失败: "+n+",数据已重新加入队列"),(r=e.batchQueue).unshift.apply(r,t),e.batchQueue.length>2*e.initConfig.batchMaxSize&&(e.batchQueue=e.batchQueue.slice(0,e.initConfig.batchMaxSize)),e.saveBatchQueueToStorage()}})},e.addToBatchQueue=function(t){var n=e.initConfig,r=n.batchInterval,i=n.batchMaxSize;e.batchQueue.push(t),e.saveBatchQueueToStorage(),e.batchQueue.length>=i?e.flushBatchQueue():e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),r))},e.restoreBatchQueueFromStorage=function(){try{var t=e.getLocalStorage(e.BATCH_QUEUE_STORAGE_KEY);if(t){var n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){e.batchQueue=n,e.initConfig.showLog&&e.printLog("从 LocalStorage 恢复 "+n.length+" 条待发送数据");var r=e.initConfig.batchMaxSize;if(e.batchQueue.length>=r)e.flushBatchQueue();else{var i=e.initConfig.batchInterval;e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),i))}}}}catch(t){e.printLog("恢复批量队列失败: "+t),e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}},e.saveBatchQueueToStorage=function(){try{if(JSON.stringify(e.batchQueue).length>4194304){var t=Math.floor(.8*e.batchQueue.length);e.batchQueue=e.batchQueue.slice(-t),e.printLog("队列过大,已截断保留最新 "+t+" 条数据")}e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,JSON.stringify(e.batchQueue))}catch(t){e.printLog("保存批量队列到 LocalStorage 失败: "+t)}},e.setupBeforeUnloadListener=function(){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e.batchQueue.length>0&&e.saveBatchQueueToStorage()})),window.addEventListener("beforeunload",(function(){if(e.batchQueue.length>0)if(navigator.sendBeacon&&e.initConfig.serverUrl)try{var t=JSON.stringify({events:e.batchQueue}),n=new Blob([t],{type:"application/json"});navigator.sendBeacon(e.initConfig.serverUrl,n),e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}catch(t){e.saveBatchQueueToStorage()}else e.saveBatchQueueToStorage()}))},e.sendData=function(t,n){if(!e.shouldSample())return Promise.resolve({success:!0,message:"数据已采样跳过"});var r=e.initConfig,i=r.serverUrl,o=r.sendTimeout,a=r.contentType,c=r.showLog,s=r.header,u=r.batchSend;return c&&e.printLog(t),u?(e.addToBatchQueue(t),Promise.resolve({success:!0,message:"已添加到批量队列"})):!0!==e.isSupportBeaconSend()||n||s?new Promise((function(r,c){e.ajax({header:n||s,url:i,type:"POST",data:JSON.stringify(t),contentType:a,credentials:!1,timeout:o,cors:!0,success:function(e){return r({success:!0,data:e})},error:function(e,t){return c({success:!1,message:String(e),code:t})}})})):e.sendBeacon({contentType:a,url:i,data:t})},e.sendRetained=function(n){var r=e.getParams({event:"PageRetained",desc:e.eventDescMap.PageRetained});if(["beforeunload","pushState","replaceState","hashchange","popstate"].indexOf(n)>=0){var i=e.getCookie("retainedStartTime"),o=i?+i:e.getTimeStamp(),a=t(t({},r),{privateParamMap:t(t({},r.privateParamMap),{retainedDuration:Math.max(r.requestTime-o,0)})});e.sendData(a),e.setCookie("retainedStartTime",e.getTimeStamp())}},e.getItemKey=function(t){return[e.initConfig.appKey,e.pageKey,t?t.toString():void 0].filter((function(e){return!!e})).reduce((function(e,t){return e+(e.length?".":"")+t}),"")},e.sdkVersion="1.2.0",e.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10},e.systemsInfo={},e}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(r,n),r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(function(){function e(){var e=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",r=[],i={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,c=t.match(/(ipod).*\s([\d_]+)/i),s=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),d=t.match(/(Mac OS X)\s([\d_]+)/i);r=[],l?(r.push("Android "+l[2]),n="h5"):u?(r.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):s?(r.push("iPad, iOS "+s[2].replace(/_/g,".")),n="ipad"):c?(r.push("iPod, iOS "+c[2].replace(/_/g,".")),n="h5"):g?(r.push("Windows "+g[2].replace(/_/g,".")),n="pc"):d&&(r.push("Mac, MacOS "+d[2].replace(/_/g,".")),n="pc"),a&&r.push("WeChat "+a),i.client=r.length?r.join(", "):"Unknown",i.platform=e||n;var h=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return h&&h[0]&&(r=[(h=h[0].split("/"))[1]],i.network=r.length?r.join(", "):"Unknown"),i.ua=t,i},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],r=new Event(e);return function(){var e=n.apply(t,arguments);return r.arguments=arguments,window.dispatchEvent(r),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(t,n,r){if(null==t)return!1;if(e.nativeForEach&&t.forEach===e.nativeForEach)t.forEach(n,r);else if(e.isArray(t)&&t.length===+t.length){for(var i=0,o=t.length;i<o;i++)if(i in t&&n.call(r,t[i],i,t)===e.breaker)return!1}else for(var a in t)if(e.hasOwnProperty.call(t,a)&&n.call(r,t[a],a,t)===e.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,r=e.parentNode.children,i=0;i<r.length;i++)if(r[i].tagName===n){if(e===r[i])return t;t++}return-1},this.selector=function(t){var n=t.parentNode&&9==t.parentNode.nodeType?-1:e.getDomIndex(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(t,n){if(!t||!t.parentNode||!t.parentNode.children)return!1;n=n&&n.join?n:[];var r=t.nodeName.toLowerCase();return t&&"body"!==r&&1==t.nodeType?(n.unshift(e.selector(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?n.join(" > "):e.getDomSelector(t.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return this._decodeURIComponent(i.substring(t.length,i.length))}return null},this.setCookie=function(e,t,n){var r,i="";n=null==n?73e3:n;var o=this.getMainHost();if(r=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),i="; expires="+a.toUTCString()}function c(e){return e||!1}var s="",u="",l="";e&&(s=c(e)),t&&(u=c(t)),r&&(l=c(r)),s&&u&&(document.cookie=s+"="+encodeURIComponent(u)+i+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(t){e.setCookie(t,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var t=e.getCookie("distinctId");return t||(t=e.uuid(),e.setCookie("distinctId",t),t)},this.filterSensitiveData=function(t,n){if(void 0===n&&(n=["password","token","secret","key"]),!e.isObject(t))return t;var r={};return e.each(t,(function(t,i){n.some((function(e){return"string"==typeof i&&i.toLowerCase().includes(e.toLowerCase())}))?r[i]="***":e.isObject(t)?r[i]=e.filterSensitiveData(t,n):r[i]=t})),r},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var r=e[n].replace(/\?|\&/,"").split("=");t[r[0]]=r[1]}return Object.keys(t).length>0?t:null},this.ajax=function(t){function r(e){if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return"object"===n(e)?e:{}}t.timeout=t.timeout||3e4,t.credentials=void 0===t.credentials||t.credentials;var i=e.xhr(t.cors);if(!i)return!1;t.type||(t.type=t.data?"POST":"GET");var o,a=t.success,c=t.error;t.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},t.error=function(e,t){c&&c(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{e.isObject(i)&&i.abort&&i.abort()}catch(t){e.printLog(t)}o&&(clearTimeout(o),o=null,t.error&&t.error(),i.onreadystatechange=null,i.onload=null,i.onerror=null)}()}),t.timeout),i.onreadystatechange=function(){try{4==i.readyState&&(i.status>=200&&i.status<300||304==i.status?t.success&&t.success(r(i.responseText)):t.error&&t.error(r(i.responseText),i.status),i.onreadystatechange=null,i.onload=null)}catch(e){i.onreadystatechange=null,i.onload=null}},i.open(t.type||"GET",t.url,!0);try{t.credentials&&(i.withCredentials=!0),e.isObject(t.header)&&e.each(t.header,(function(e,t){i.setRequestHeader&&i.setRequestHeader(t,e)})),t.data&&(t.cors||i.setRequestHeader&&i.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===t.contentType?i.setRequestHeader&&i.setRequestHeader("Content-type","application/json; charset=UTF-8"):i.setRequestHeader&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(t){e.printLog(t)}i.send(t.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var t=!1;if("object"!==("undefined"==typeof navigator?"undefined":n(navigator))||"function"!=typeof navigator.sendBeacon)return t;var r=e.getUA(),i=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(i.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===r.safari&&(r.safari=Number(o[0])),o[0]&&+o[0]<13?(r.chrome>41||r.firefox>30||r.opera>25||r.safari>12)&&(t=!0):(r.chrome>41||r.firefox>30||r.opera>25||r.safari>11.3)&&(t=!0)}else(r.chrome>38||r.edge>13||r.firefox>30||r.opera>25||r.safari>11)&&(t=!0);return t},this.throttle=function(e,t){var n=null,r=0;return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var a=Date.now(),c=t-(a-r);c<=0||c>t?(n&&(clearTimeout(n),n=null),r=a,e.apply(void 0,i)):n||(n=window.setTimeout((function(){r=Date.now(),n=null,e.apply(void 0,i)}),c))}},this.debounce=function(e,t){var n=null;return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,r)}),t)}},this.sendBeacon=function(t){if(!0===e.isSupportBeaconSend()){var n={type:t.contentType},r=new Blob([JSON.stringify(t.data)],n);return navigator.sendBeacon(t.url,r)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return t;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),r},this.collectFingerprint=function(){var t={};return t.userAgent=navigator.userAgent,t.screenWidth=screen.width,t.screenHeight=screen.height,t.colorDepth=screen.colorDepth,t.pixelDepth=screen.pixelDepth,t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.timezoneOffset=(new Date).getTimezoneOffset(),t.language=navigator.language,t.languages=Array.from(navigator.languages),t.platform=navigator.platform,t.webgl=e.getWebGLFingerprint(),t.canvas=e.getCanvasFingerprint(),t.audio=e.getAudioFingerprint(),t.fonts=e.getFontFingerprint(),t.plugins=e.getPluginsFingerprint(),t.localStorage=e.hasLocalStorage(),t.sessionStorage=e.hasSessionStorage(),t.indexedDB=e.hasIndexedDB(),t.hardwareConcurrency=navigator.hardwareConcurrency,t.deviceMemory=navigator.deviceMemory,t.maxTouchPoints=navigator.maxTouchPoints,t.connection=e.getConnectionFingerprint(),t},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=t.createOscillator(),r=t.createAnalyser(),i=t.createGain(),o=t.createScriptProcessor(4096,1,1);n.type="triangle",n.frequency.value=1e4,i.gain.value=0,n.connect(r),r.connect(o),o.connect(i),i.connect(t.destination),n.start(0);var a=t.sampleRate+"|"+t.currentTime;return n.stop(),t.close(),a}catch(e){return"error"}},this.getFontFingerprint=function(){try{var e=["monospace","sans-serif","serif"],t="mmmmmmmmmmlli",n=document.createElement("canvas").getContext("2d");if(!n)return"not-supported";var r=[],i={};return e.forEach((function(e){n.font="72px "+e,i[e]=n.measureText(t).width})),["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Helvetica","Impact","Times New Roman","Trebuchet MS","Verdana"].forEach((function(o){var a=!1;e.forEach((function(e){n.font="72px '"+o+"', "+e,n.measureText(t).width!==i[e]&&(a=!0)})),a&&r.push(o)})),r.join(",")}catch(e){return"error"}},this.getPluginsFingerprint=function(){try{var e=[];if(navigator.plugins)for(var t=0;t<navigator.plugins.length;t++){var n=navigator.plugins[t];n&&e.push(n.name+"|"+n.description+"|"+n.filename)}return e.join(";")}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.getConnectionFingerprint=function(){try{var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?e.effectiveType+"|"+e.downlink+"|"+e.rtt:"not-supported"}catch(e){return"error"}},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,r=52711,i=0;i<t.length;i++){var o=t.charCodeAt(i);n=(n<<5)+n+o,r=(r<<5)+r+o}return"fp_"+(4096*(n>>>0)+(r>>>0)).toString(36)}}return e.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.isObject(e[0])&&(e[0]=this.formatJsonString(e[0])),"object"===("undefined"==typeof console?"undefined":n(console))&&console.log)try{return console.log.apply(console,e)}catch(t){console.log(e[0])}},e.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},e.prototype.isUndefined=function(e){return void 0===e},e.prototype.isString=function(e){return"[object String]"==toString.call(e)},e.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},e.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},e.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},e.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},e.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},e.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},e.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},e.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),r=document.domain,i=r.split("."),o=[];for(o.unshift(i.pop());i.length;){o.unshift(i.pop());var a=o.join("."),c=e+"=12345;domain=."+a;if(document.cookie=c,t.test(document.cookie))return document.cookie=c+";expires="+n,a}return r},e}()))}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).WebTracking=t()}(this,(function(){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(t,n)};var t=function(){return(t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}return new(function(n){function r(){var e=n.call(this)||this;return e.batchQueue=[],e.batchTimer=null,e.BATCH_QUEUE_STORAGE_KEY="web_tracking_batch_queue",e.useCustomPageKey=!1,e.userInfo=null,e.currentUrl="",e.pageKey="",e.deviceId="",e.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报"},e.init=function(t){e.preset(t);var n=window.location.pathname;e.currentUrl=window.location.href,t.pageKey?(e.pageKey=t.pageKey,e.useCustomPageKey=!0):(e.pageKey=n.replace(/\//g,"_").substring(1),e.useCustomPageKey=!1),e.systemsInfo=e.getSystemsInfo(t.platform),e.deviceId=e.getDeviceId(),e.setCookie("retainedStartTime",e.getTimeStamp()),e.initConfig.batchSend&&(e.restoreBatchQueueFromStorage(),e.setupBeforeUnloadListener())},e.preset=function(t){if(t instanceof Object){if(void 0!==t.pageKey)if(null===t.pageKey||""===t.pageKey){e.useCustomPageKey=!1;var n=window.location.pathname;e.pageKey=n.replace(/\//g,"_").substring(1)}else e.pageKey=t.pageKey,e.useCustomPageKey=!0;e.each(t,(function(t,n){"pageKey"!==n&&e.initConfig.hasOwnProperty(n)&&(e.initConfig[n]=t)}))}/^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-\(\)]*[\w@?^=%&/~+#-\(\)])?$/.test(e.initConfig.serverUrl)||(e.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),e.initConfig.showLog=!0),e.initConfig.autoTrack?e.listener():e.unlistener()},e.login=function(t){e.isObject(t)&&(e.userInfo=t)},e.getDeviceId=function(){if(e.deviceId)return e.deviceId;var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return e.deviceId=t,e.deviceId;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),e.deviceId=r,e.deviceId},e.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),e.deviceId="",e.getDeviceId()},e.track=function(t){var n=t.desc,r=t.pageKey,i=t.partkey,o=t.business,a=t.header,c=e.getParams({desc:n,event:"CustomTrack",itemKey:e.getItemKey(i,r),privateParamMap:{business:o}});return e.sendData(c,a)},e.listener=function(){e.initConfig.isTrackSinglePage&&(e.rewriteHistory(),e.addSinglePageEvent(e.onPageViewCallback)),e.each(["load","beforeunload"],(function(t){e.addEventListener(window,t,e.onPageViewCallback)})),e.addEventListener(window,"click",e.onClickCallback)},e.unlistener=function(){if(e.initConfig.isTrackSinglePage){var t=window.history.pushState?"popstate":"hashchange";e.each(["pushState","replaceState",t],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)}))}e.each(["load","beforeunload"],(function(t){e.removeEventListener(window,t,e.onPageViewCallback)})),e.removeEventListener(window,"click",e.onClickCallback),e.clearBatchTimer()},e.clearBatchTimer=function(){null!==e.batchTimer&&(clearTimeout(e.batchTimer),e.batchTimer=null)},e.clearBatchQueue=function(){e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]"),e.initConfig.showLog&&e.printLog("批量队列已清空")},e.setPageKey=function(t,n){if(void 0===n&&(n=!1),null===t||""===t){e.useCustomPageKey=!1;var r=window.location.pathname;e.pageKey=r.replace(/\//g,"_").substring(1),e.initConfig.showLog&&e.printLog("页面标识已恢复自动生成: "+e.pageKey)}else e.pageKey=t,e.useCustomPageKey=!n,e.initConfig.showLog&&e.printLog("页面标识已设置为: "+t+", 自动更新: "+n)},e.getPageKey=function(){return e.pageKey},e.onClickCallback=function(t){var n,r=t.target;if(null===(n=null==r?void 0:r.dataset)||void 0===n?void 0:n.partKey){var i=[t.pageX,t.pageY],o=r.id,a=r.className,c={id:o,nodeName:r.nodeName,className:a,position:i},s=e.getParams({event:"WebClick",desc:e.eventDescMap.WebClick,itemKey:e.getItemKey(r.dataset.partKey),privateParamMap:{targetEle:c,pointerType:t.pointerType,currentUrl:e.currentUrl,elementSelector:e.getDomSelector(r)||""}});return e.sendData(s)}},e.onPageViewCallback=function(t){var n,r,i=window.location.origin,o=e.getParams({event:"PageView",desc:e.eventDescMap.PageView,privateParamMap:{currentUrl:e.currentUrl,targetUrl:(null===(n=t.arguments)||void 0===n?void 0:n[2])?i+(null===(r=t.arguments)||void 0===r?void 0:r[2]):null}});e.currentUrl=window.location.href,e.useCustomPageKey||(e.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),e.sendRetained(t.type),e.sendData(o)},e.getParams=function(t){var n=t.event,r=t.desc,i=t.privateParamMap,o=void 0===i?{}:i,a=t.itemKey,c=e.initConfig.business,s=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,d=e.filterSensitiveData(c||{}),p=e.filterSensitiveData(e.userInfo||{}),h=e.filterSensitiveData(o||{}),f=e.filterSensitiveData(e.getQueryValue()||{}),m={currentUrl:h.currentUrl||e.currentUrl,business:Object.assign({},d,h.business||{}),pageWidth:s,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:e.sdkVersion,systemsInfo:e.systemsInfo,urlParams:f,userInfo:p,deviceId:e.deviceId};return h.targetEle&&(m.targetEle=h.targetEle),h.targetUrl&&(m.targetUrl=h.targetUrl),h.pointerType&&(m.pointerType=h.pointerType),h.elementSelector&&(m.elementSelector=h.elementSelector),h.retainedDuration&&(m.retainedDuration=h.retainedDuration),{event:n,desc:r,itemKey:a||e.getItemKey(),requestTime:e.getTimeStamp(),privateParamMap:m}},e.shouldSample=function(){var t=e.initConfig.sampleRate;return t>=1||!(t<=0)&&Math.random()<t},e.flushBatchQueue=function(){if(0!==e.batchQueue.length){var t=function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e}([],e.batchQueue);e.batchQueue=[],e.saveBatchQueueToStorage(),e.sendBatchData(t)}},e.sendBatchData=function(t){var n=e.initConfig,r=n.serverUrl,i=n.contentType;n.showLog&&(e.printLog("批量发送 "+t.length+" 条数据"),t.forEach((function(t){return e.printLog(t)}))),e.ajax({url:r,type:"POST",data:JSON.stringify({events:t}),contentType:i,credentials:!1,timeout:e.initConfig.sendTimeout,cors:!0,success:function(){e.initConfig.showLog&&e.printLog("批量发送成功: "+t.length+" 条数据")},error:function(n){var r;e.printLog("批量发送失败: "+n+",数据已重新加入队列"),(r=e.batchQueue).unshift.apply(r,t),e.batchQueue.length>2*e.initConfig.batchMaxSize&&(e.batchQueue=e.batchQueue.slice(0,e.initConfig.batchMaxSize)),e.saveBatchQueueToStorage()}})},e.addToBatchQueue=function(t){var n=e.initConfig,r=n.batchInterval,i=n.batchMaxSize;e.batchQueue.push(t),e.saveBatchQueueToStorage(),e.batchQueue.length>=i?e.flushBatchQueue():e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),r))},e.restoreBatchQueueFromStorage=function(){try{var t=e.getLocalStorage(e.BATCH_QUEUE_STORAGE_KEY);if(t){var n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){e.batchQueue=n,e.initConfig.showLog&&e.printLog("从 LocalStorage 恢复 "+n.length+" 条待发送数据");var r=e.initConfig.batchMaxSize;if(e.batchQueue.length>=r)e.flushBatchQueue();else{var i=e.initConfig.batchInterval;e.batchTimer||(e.batchTimer=window.setTimeout((function(){e.flushBatchQueue(),e.batchTimer=null}),i))}}}}catch(t){e.printLog("恢复批量队列失败: "+t),e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}},e.saveBatchQueueToStorage=function(){try{if(JSON.stringify(e.batchQueue).length>4194304){var t=Math.floor(.8*e.batchQueue.length);e.batchQueue=e.batchQueue.slice(-t),e.printLog("队列过大,已截断保留最新 "+t+" 条数据")}e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,JSON.stringify(e.batchQueue))}catch(t){e.printLog("保存批量队列到 LocalStorage 失败: "+t)}},e.setupBeforeUnloadListener=function(){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e.batchQueue.length>0&&e.saveBatchQueueToStorage()})),window.addEventListener("beforeunload",(function(){if(e.batchQueue.length>0)if(navigator.sendBeacon&&e.initConfig.serverUrl)try{var t=JSON.stringify({events:e.batchQueue}),n=new Blob([t],{type:"application/json"});navigator.sendBeacon(e.initConfig.serverUrl,n),e.batchQueue=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]")}catch(t){e.saveBatchQueueToStorage()}else e.saveBatchQueueToStorage()}))},e.sendData=function(t,n){if(!e.shouldSample())return Promise.resolve({success:!0,message:"数据已采样跳过"});var r=e.initConfig,i=r.serverUrl,o=r.sendTimeout,a=r.contentType,c=r.showLog,s=r.header,u=r.batchSend;return c&&e.printLog(t),u?(e.addToBatchQueue(t),Promise.resolve({success:!0,message:"已添加到批量队列"})):!0!==e.isSupportBeaconSend()||n||s?new Promise((function(r,c){e.ajax({header:n||s,url:i,type:"POST",data:JSON.stringify(t),contentType:a,credentials:!1,timeout:o,cors:!0,success:function(e){return r({success:!0,data:e})},error:function(e,t){return c({success:!1,message:String(e),code:t})}})})):e.sendBeacon({contentType:a,url:i,data:t})},e.sendRetained=function(n){var r=e.getParams({event:"PageRetained",desc:e.eventDescMap.PageRetained});if(["beforeunload","pushState","replaceState","hashchange","popstate"].indexOf(n)>=0){var i=e.getCookie("retainedStartTime"),o=i?+i:e.getTimeStamp(),a=t(t({},r),{privateParamMap:t(t({},r.privateParamMap),{retainedDuration:Math.max(r.requestTime-o,0)})});e.sendData(a),e.setCookie("retainedStartTime",e.getTimeStamp())}},e.getItemKey=function(t,n){return[e.initConfig.appKey,(n||e.pageKey).toString(),t?t.toString():void 0].filter((function(e){return!!e})).reduce((function(e,t){return e+(e.length?".":"")+t}),"")},e.sdkVersion="1.2.0",e.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10},e.systemsInfo={},e}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(r,n),r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(function(){function e(){var e=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",r=[],i={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,c=t.match(/(ipod).*\s([\d_]+)/i),s=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),d=t.match(/(Mac OS X)\s([\d_]+)/i);r=[],l?(r.push("Android "+l[2]),n="h5"):u?(r.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):s?(r.push("iPad, iOS "+s[2].replace(/_/g,".")),n="ipad"):c?(r.push("iPod, iOS "+c[2].replace(/_/g,".")),n="h5"):g?(r.push("Windows "+g[2].replace(/_/g,".")),n="pc"):d&&(r.push("Mac, MacOS "+d[2].replace(/_/g,".")),n="pc"),a&&r.push("WeChat "+a),i.client=r.length?r.join(", "):"Unknown",i.platform=e||n;var p=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return p&&p[0]&&(r=[(p=p[0].split("/"))[1]],i.network=r.length?r.join(", "):"Unknown"),i.ua=t,i},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],r=new Event(e);return function(){var e=n.apply(t,arguments);return r.arguments=arguments,window.dispatchEvent(r),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(t,n,r){if(null==t)return!1;if(e.nativeForEach&&t.forEach===e.nativeForEach)t.forEach(n,r);else if(e.isArray(t)&&t.length===+t.length){for(var i=0,o=t.length;i<o;i++)if(i in t&&n.call(r,t[i],i,t)===e.breaker)return!1}else for(var a in t)if(e.hasOwnProperty.call(t,a)&&n.call(r,t[a],a,t)===e.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,r=e.parentNode.children,i=0;i<r.length;i++)if(r[i].tagName===n){if(e===r[i])return t;t++}return-1},this.selector=function(t){var n=t.parentNode&&9==t.parentNode.nodeType?-1:e.getDomIndex(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(t,n){if(!t||!t.parentNode||!t.parentNode.children)return!1;n=n&&n.join?n:[];var r=t.nodeName.toLowerCase();return t&&"body"!==r&&1==t.nodeType?(n.unshift(e.selector(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?n.join(" > "):e.getDomSelector(t.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return this._decodeURIComponent(i.substring(t.length,i.length))}return null},this.setCookie=function(e,t,n){var r,i="";n=null==n?73e3:n;var o=this.getMainHost();if(r=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),i="; expires="+a.toUTCString()}function c(e){return e||!1}var s="",u="",l="";e&&(s=c(e)),t&&(u=c(t)),r&&(l=c(r)),s&&u&&(document.cookie=s+"="+encodeURIComponent(u)+i+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(t){e.setCookie(t,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var t=e.getCookie("distinctId");return t||(t=e.uuid(),e.setCookie("distinctId",t),t)},this.filterSensitiveData=function(t,n){if(void 0===n&&(n=["password","token","secret","key"]),!e.isObject(t))return t;var r={};return e.each(t,(function(t,i){n.some((function(e){return"string"==typeof i&&i.toLowerCase().includes(e.toLowerCase())}))?r[i]="***":e.isObject(t)?r[i]=e.filterSensitiveData(t,n):r[i]=t})),r},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var r=e[n].replace(/\?|\&/,"").split("=");t[r[0]]=r[1]}return Object.keys(t).length>0?t:null},this.ajax=function(t){function r(e){if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return"object"===n(e)?e:{}}t.timeout=t.timeout||3e4,t.credentials=void 0===t.credentials||t.credentials;var i=e.xhr(t.cors);if(!i)return!1;t.type||(t.type=t.data?"POST":"GET");var o,a=t.success,c=t.error;t.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},t.error=function(e,t){c&&c(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{e.isObject(i)&&i.abort&&i.abort()}catch(t){e.printLog(t)}o&&(clearTimeout(o),o=null,t.error&&t.error(),i.onreadystatechange=null,i.onload=null,i.onerror=null)}()}),t.timeout),i.onreadystatechange=function(){try{4==i.readyState&&(i.status>=200&&i.status<300||304==i.status?t.success&&t.success(r(i.responseText)):t.error&&t.error(r(i.responseText),i.status),i.onreadystatechange=null,i.onload=null)}catch(e){i.onreadystatechange=null,i.onload=null}},i.open(t.type||"GET",t.url,!0);try{t.credentials&&(i.withCredentials=!0),e.isObject(t.header)&&e.each(t.header,(function(e,t){i.setRequestHeader&&i.setRequestHeader(t,e)})),t.data&&(t.cors||i.setRequestHeader&&i.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===t.contentType?i.setRequestHeader&&i.setRequestHeader("Content-type","application/json; charset=UTF-8"):i.setRequestHeader&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(t){e.printLog(t)}i.send(t.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var t=!1;if("object"!==("undefined"==typeof navigator?"undefined":n(navigator))||"function"!=typeof navigator.sendBeacon)return t;var r=e.getUA(),i=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(i.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===r.safari&&(r.safari=Number(o[0])),o[0]&&+o[0]<13?(r.chrome>41||r.firefox>30||r.opera>25||r.safari>12)&&(t=!0):(r.chrome>41||r.firefox>30||r.opera>25||r.safari>11.3)&&(t=!0)}else(r.chrome>38||r.edge>13||r.firefox>30||r.opera>25||r.safari>11)&&(t=!0);return t},this.throttle=function(e,t){var n=null,r=0;return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var a=Date.now(),c=t-(a-r);c<=0||c>t?(n&&(clearTimeout(n),n=null),r=a,e.apply(void 0,i)):n||(n=window.setTimeout((function(){r=Date.now(),n=null,e.apply(void 0,i)}),c))}},this.debounce=function(e,t){var n=null;return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,r)}),t)}},this.sendBeacon=function(t){if(!0===e.isSupportBeaconSend()){var n={type:t.contentType},r=new Blob([JSON.stringify(t.data)],n);return navigator.sendBeacon(t.url,r)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var t=e.getCookie("device_id")||e.getLocalStorage("device_id");if(t)return t;var n=e.collectFingerprint(),r=e.hashFingerprint(n);return e.setCookie("device_id",r,730),e.setLocalStorage("device_id",r),r},this.collectFingerprint=function(){var t={};return t.userAgent=navigator.userAgent,t.screenWidth=screen.width,t.screenHeight=screen.height,t.colorDepth=screen.colorDepth,t.pixelDepth=screen.pixelDepth,t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.timezoneOffset=(new Date).getTimezoneOffset(),t.language=navigator.language,t.languages=Array.from(navigator.languages),t.platform=navigator.platform,t.webgl=e.getWebGLFingerprint(),t.canvas=e.getCanvasFingerprint(),t.audio=e.getAudioFingerprint(),t.fonts=e.getFontFingerprint(),t.plugins=e.getPluginsFingerprint(),t.localStorage=e.hasLocalStorage(),t.sessionStorage=e.hasSessionStorage(),t.indexedDB=e.hasIndexedDB(),t.hardwareConcurrency=navigator.hardwareConcurrency,t.deviceMemory=navigator.deviceMemory,t.maxTouchPoints=navigator.maxTouchPoints,t.connection=e.getConnectionFingerprint(),t},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=t.createOscillator(),r=t.createAnalyser(),i=t.createGain(),o=t.createScriptProcessor(4096,1,1);n.type="triangle",n.frequency.value=1e4,i.gain.value=0,n.connect(r),r.connect(o),o.connect(i),i.connect(t.destination),n.start(0);var a=t.sampleRate+"|"+t.currentTime;return n.stop(),t.close(),a}catch(e){return"error"}},this.getFontFingerprint=function(){try{var e=["monospace","sans-serif","serif"],t="mmmmmmmmmmlli",n=document.createElement("canvas").getContext("2d");if(!n)return"not-supported";var r=[],i={};return e.forEach((function(e){n.font="72px "+e,i[e]=n.measureText(t).width})),["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Helvetica","Impact","Times New Roman","Trebuchet MS","Verdana"].forEach((function(o){var a=!1;e.forEach((function(e){n.font="72px '"+o+"', "+e,n.measureText(t).width!==i[e]&&(a=!0)})),a&&r.push(o)})),r.join(",")}catch(e){return"error"}},this.getPluginsFingerprint=function(){try{var e=[];if(navigator.plugins)for(var t=0;t<navigator.plugins.length;t++){var n=navigator.plugins[t];n&&e.push(n.name+"|"+n.description+"|"+n.filename)}return e.join(";")}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.getConnectionFingerprint=function(){try{var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?e.effectiveType+"|"+e.downlink+"|"+e.rtt:"not-supported"}catch(e){return"error"}},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,r=52711,i=0;i<t.length;i++){var o=t.charCodeAt(i);n=(n<<5)+n+o,r=(r<<5)+r+o}return"fp_"+(4096*(n>>>0)+(r>>>0)).toString(36)}}return e.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.isObject(e[0])&&(e[0]=this.formatJsonString(e[0])),"object"===("undefined"==typeof console?"undefined":n(console))&&console.log)try{return console.log.apply(console,e)}catch(t){console.log(e[0])}},e.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},e.prototype.isUndefined=function(e){return void 0===e},e.prototype.isString=function(e){return"[object String]"==toString.call(e)},e.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},e.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},e.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},e.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},e.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},e.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},e.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},e.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),r=document.domain,i=r.split("."),o=[];for(o.unshift(i.pop());i.length;){o.unshift(i.pop());var a=o.join("."),c=e+"=12345;domain=."+a;if(document.cookie=c,t.test(document.cookie))return document.cookie=c+";expires="+n,a}return r},e}()))}));
|
package/lib/types/index.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ declare class WebTracking extends Tools {
|
|
|
16
16
|
private batchQueue;
|
|
17
17
|
private batchTimer;
|
|
18
18
|
private readonly BATCH_QUEUE_STORAGE_KEY;
|
|
19
|
+
private useCustomPageKey;
|
|
19
20
|
constructor();
|
|
20
21
|
protected userInfo?: JsonProps;
|
|
21
22
|
protected currentUrl: string;
|
|
@@ -53,7 +54,7 @@ declare class WebTracking extends Tools {
|
|
|
53
54
|
* @param {object} TrackParams [自定义上报参数]
|
|
54
55
|
* @return {Promise<TrackingResponse>} [回调]
|
|
55
56
|
*/
|
|
56
|
-
track: ({ desc, partkey, business, header }: TrackParams) => Promise<TrackingResponse>;
|
|
57
|
+
track: ({ desc, pageKey, partkey, business, header }: TrackParams) => Promise<TrackingResponse>;
|
|
57
58
|
/**
|
|
58
59
|
* @description 监听全埋点事件
|
|
59
60
|
*/
|
|
@@ -70,6 +71,17 @@ declare class WebTracking extends Tools {
|
|
|
70
71
|
* @description 清空批量队列(包括 LocalStorage 中的数据)
|
|
71
72
|
*/
|
|
72
73
|
clearBatchQueue: () => void;
|
|
74
|
+
/**
|
|
75
|
+
* @description 设置自定义页面唯一标识
|
|
76
|
+
* @param pageKey 页面唯一标识,如果传入 null 或空字符串,则恢复自动生成
|
|
77
|
+
* @param autoUpdate 路由变化时是否自动更新(默认:false,使用自定义值后不再自动更新)
|
|
78
|
+
*/
|
|
79
|
+
setPageKey: (pageKey: string | null, autoUpdate?: boolean) => void;
|
|
80
|
+
/**
|
|
81
|
+
* @description 获取当前页面唯一标识
|
|
82
|
+
* @returns 当前页面唯一标识
|
|
83
|
+
*/
|
|
84
|
+
getPageKey: () => string;
|
|
73
85
|
protected onClickCallback: (e: MouseEvent) => Promise<TrackingResponse>;
|
|
74
86
|
/**
|
|
75
87
|
* @description 添加单页面监听事件
|
|
@@ -80,7 +92,7 @@ declare class WebTracking extends Tools {
|
|
|
80
92
|
* @description 路由触发事件
|
|
81
93
|
*/
|
|
82
94
|
protected onPageViewCallback: (e: EventParams) => void;
|
|
83
|
-
getParams: ({ event, desc, privateParamMap, itemKey
|
|
95
|
+
getParams: ({ event, desc, privateParamMap, itemKey }: GetParamsOptions) => TrackingPostParams;
|
|
84
96
|
/**
|
|
85
97
|
* 数据采样判断
|
|
86
98
|
* @returns 是否应该采样
|
|
@@ -126,7 +138,7 @@ declare class WebTracking extends Tools {
|
|
|
126
138
|
* @param {[string]} partkey [控件/自定义事件的唯一标识]
|
|
127
139
|
* @return {[string]}
|
|
128
140
|
*/
|
|
129
|
-
protected getItemKey: (partkey?: string | number) => string;
|
|
141
|
+
protected getItemKey: (partkey?: string | number, pageKey?: string | number) => string;
|
|
130
142
|
}
|
|
131
143
|
declare const _default: WebTracking;
|
|
132
144
|
export default _default;
|
package/lib/types/type.d.ts
CHANGED
|
@@ -107,6 +107,11 @@ export interface PresetParams {
|
|
|
107
107
|
* @default 10
|
|
108
108
|
*/
|
|
109
109
|
batchMaxSize?: number;
|
|
110
|
+
/**
|
|
111
|
+
* @description 自定义页面唯一标识,如果不传则自动从路由获取
|
|
112
|
+
* @default 自动从 window.location.pathname 获取
|
|
113
|
+
*/
|
|
114
|
+
pageKey?: string;
|
|
110
115
|
}
|
|
111
116
|
export interface InitParams extends PresetParams {
|
|
112
117
|
/**
|
|
@@ -136,6 +141,10 @@ export interface SystemsInfoTypes {
|
|
|
136
141
|
platform?: PlatformType | string;
|
|
137
142
|
}
|
|
138
143
|
export interface TrackParams {
|
|
144
|
+
/**
|
|
145
|
+
* @description 页面唯一标识
|
|
146
|
+
*/
|
|
147
|
+
pageKey?: string;
|
|
139
148
|
/**
|
|
140
149
|
* @description 控件/自定义事件的唯一标识
|
|
141
150
|
*/
|