@fle-sdk/event-tracking-web 1.2.1 → 1.2.2
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/lib/index.esm.js +326 -45
- package/lib/index.esm.min.js +1 -1
- package/lib/index.js +326 -45
- package/lib/index.min.js +1 -1
- package/lib/types/index.d.ts +37 -1
- package/lib/types/type.d.ts +14 -0
- package/package.json +1 -1
package/lib/index.esm.js
CHANGED
|
@@ -1248,7 +1248,17 @@ function (_super) {
|
|
|
1248
1248
|
|
|
1249
1249
|
_this.BATCH_QUEUE_STORAGE_KEY = "web_tracking_batch_queue"; // 是否使用自定义 pageKey(如果为 true,路由变化时不会自动更新 pageKey)
|
|
1250
1250
|
|
|
1251
|
-
_this.useCustomPageKey = false; //
|
|
1251
|
+
_this.useCustomPageKey = false; // 待发送的单个请求队列(用于页面跳转时发送)
|
|
1252
|
+
|
|
1253
|
+
_this.pendingRequests = []; // 页面卸载监听器是否已设置
|
|
1254
|
+
|
|
1255
|
+
_this.isUnloadListenerSetup = false; // LocalStorage 存储 key(待发送请求)
|
|
1256
|
+
|
|
1257
|
+
_this.PENDING_REQUESTS_STORAGE_KEY = "web_tracking_pending_requests"; // 待发送请求队列最大大小(默认值,可通过配置覆盖)
|
|
1258
|
+
|
|
1259
|
+
_this.DEFAULT_PENDING_REQUESTS_MAX_SIZE = 50; // LocalStorage 最大大小限制(4MB)
|
|
1260
|
+
|
|
1261
|
+
_this.MAX_STORAGE_SIZE = 4 * 1024 * 1024; // 用户信息
|
|
1252
1262
|
|
|
1253
1263
|
_this.userInfo = null; // 当前路由
|
|
1254
1264
|
|
|
@@ -1285,17 +1295,24 @@ function (_super) {
|
|
|
1285
1295
|
|
|
1286
1296
|
_this.systemsInfo = _this.getSystemsInfo(initParams.platform); // 获取设备ID
|
|
1287
1297
|
|
|
1288
|
-
_this.deviceId = _this.getDeviceId();
|
|
1298
|
+
_this.deviceId = _this.getDeviceId(); // 如果传入了 userInfo,设置用户信息
|
|
1299
|
+
|
|
1300
|
+
if (initParams.userInfo && _this.isObject(initParams.userInfo)) {
|
|
1301
|
+
_this.userInfo = initParams.userInfo;
|
|
1302
|
+
}
|
|
1289
1303
|
|
|
1290
1304
|
_this.setCookie("retainedStartTime", _this.getTimeStamp()); // 如果启用了批量发送,从 LocalStorage 恢复队列
|
|
1291
1305
|
|
|
1292
1306
|
|
|
1293
1307
|
if (_this.initConfig.batchSend) {
|
|
1294
|
-
_this.restoreBatchQueueFromStorage();
|
|
1308
|
+
_this.restoreBatchQueueFromStorage();
|
|
1309
|
+
} // 恢复待发送的单个请求
|
|
1295
1310
|
|
|
1296
1311
|
|
|
1297
|
-
|
|
1298
|
-
|
|
1312
|
+
_this.restorePendingRequestsFromStorage(); // 无论是否启用批量发送,都需要监听页面卸载事件,确保数据发送
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
_this.setupBeforeUnloadListener();
|
|
1299
1316
|
};
|
|
1300
1317
|
/**
|
|
1301
1318
|
* TODO: 需要判断有哪些不能被预制的参数
|
|
@@ -1334,10 +1351,10 @@ function (_super) {
|
|
|
1334
1351
|
_this.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!");
|
|
1335
1352
|
|
|
1336
1353
|
_this.initConfig["showLog"] = true;
|
|
1337
|
-
} //
|
|
1354
|
+
} // 如果启用了全埋点或启用了 data-part-key 点击追踪
|
|
1338
1355
|
|
|
1339
1356
|
|
|
1340
|
-
if (!!_this.initConfig["autoTrack"]) {
|
|
1357
|
+
if (!!_this.initConfig["autoTrack"] || !!_this.initConfig["trackPartKeyClick"]) {
|
|
1341
1358
|
// 启用监听
|
|
1342
1359
|
_this.listener();
|
|
1343
1360
|
} else {
|
|
@@ -1437,17 +1454,23 @@ function (_super) {
|
|
|
1437
1454
|
|
|
1438
1455
|
|
|
1439
1456
|
_this.listener = function () {
|
|
1440
|
-
|
|
1441
|
-
|
|
1457
|
+
// 如果启用了全埋点,监听页面浏览事件
|
|
1458
|
+
if (!!_this.initConfig.autoTrack) {
|
|
1459
|
+
if (!!_this.initConfig.isTrackSinglePage) {
|
|
1460
|
+
_this.rewriteHistory();
|
|
1442
1461
|
|
|
1443
|
-
|
|
1444
|
-
|
|
1462
|
+
_this.addSinglePageEvent(_this.onPageViewCallback);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
_this.each(["load", "beforeunload"], function (historyType) {
|
|
1466
|
+
_this.addEventListener(window, historyType, _this.onPageViewCallback);
|
|
1467
|
+
});
|
|
1468
|
+
} // 如果启用了全埋点或启用了 data-part-key 点击追踪,监听点击事件
|
|
1445
1469
|
|
|
1446
|
-
_this.each(["load", "beforeunload"], function (historyType) {
|
|
1447
|
-
_this.addEventListener(window, historyType, _this.onPageViewCallback);
|
|
1448
|
-
});
|
|
1449
1470
|
|
|
1450
|
-
_this.
|
|
1471
|
+
if (!!_this.initConfig.autoTrack || !!_this.initConfig.trackPartKeyClick) {
|
|
1472
|
+
_this.addEventListener(window, "click", _this.onClickCallback);
|
|
1473
|
+
}
|
|
1451
1474
|
};
|
|
1452
1475
|
/**
|
|
1453
1476
|
* @description 取消全埋点事件
|
|
@@ -1574,7 +1597,12 @@ function (_super) {
|
|
|
1574
1597
|
|
|
1575
1598
|
|
|
1576
1599
|
_this.onPageViewCallback = function (e) {
|
|
1577
|
-
var _a, _b;
|
|
1600
|
+
var _a, _b; // 在路由变化前,先发送待发送的数据(避免被取消)
|
|
1601
|
+
|
|
1602
|
+
|
|
1603
|
+
if (_this.pendingRequests.length > 0 || _this.initConfig.batchSend && _this.batchQueue.length > 0) {
|
|
1604
|
+
_this.flushPendingData();
|
|
1605
|
+
}
|
|
1578
1606
|
|
|
1579
1607
|
var ORGIN = window.location.origin;
|
|
1580
1608
|
|
|
@@ -1825,6 +1853,118 @@ function (_super) {
|
|
|
1825
1853
|
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
1826
1854
|
}
|
|
1827
1855
|
};
|
|
1856
|
+
/**
|
|
1857
|
+
* 添加到待发送请求队列
|
|
1858
|
+
* @param params 数据参数
|
|
1859
|
+
*/
|
|
1860
|
+
|
|
1861
|
+
|
|
1862
|
+
_this.addToPendingRequests = function (params) {
|
|
1863
|
+
_this.pendingRequests.push(params); // 限制队列大小,防止内存溢出
|
|
1864
|
+
|
|
1865
|
+
|
|
1866
|
+
var maxSize = _this.initConfig.pendingRequestsMaxSize || _this.DEFAULT_PENDING_REQUESTS_MAX_SIZE;
|
|
1867
|
+
|
|
1868
|
+
if (_this.pendingRequests.length > maxSize) {
|
|
1869
|
+
_this.pendingRequests = _this.pendingRequests.slice(-maxSize);
|
|
1870
|
+
|
|
1871
|
+
if (_this.initConfig.showLog) {
|
|
1872
|
+
_this.printLog("\u5F85\u53D1\u9001\u8BF7\u6C42\u961F\u5217\u5DF2\u6EE1\uFF0C\u5DF2\u79FB\u9664\u6700\u65E7\u7684\u6570\u636E\uFF08\u6700\u5927\u9650\u5236: " + maxSize + "\uFF09");
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
};
|
|
1876
|
+
/**
|
|
1877
|
+
* 从 LocalStorage 恢复待发送请求
|
|
1878
|
+
*/
|
|
1879
|
+
|
|
1880
|
+
|
|
1881
|
+
_this.restorePendingRequestsFromStorage = function () {
|
|
1882
|
+
try {
|
|
1883
|
+
var storedRequests = _this.getLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY);
|
|
1884
|
+
|
|
1885
|
+
if (storedRequests) {
|
|
1886
|
+
var parsedRequests = JSON.parse(storedRequests);
|
|
1887
|
+
|
|
1888
|
+
if (Array.isArray(parsedRequests) && parsedRequests.length > 0) {
|
|
1889
|
+
_this.pendingRequests = parsedRequests;
|
|
1890
|
+
|
|
1891
|
+
if (_this.initConfig.showLog) {
|
|
1892
|
+
_this.printLog("\u4ECE LocalStorage \u6062\u590D " + parsedRequests.length + " \u6761\u5F85\u53D1\u9001\u8BF7\u6C42");
|
|
1893
|
+
} // 恢复后立即尝试发送
|
|
1894
|
+
|
|
1895
|
+
|
|
1896
|
+
if (_this.pendingRequests.length > 0) {
|
|
1897
|
+
_this.flushPendingRequests();
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
} catch (e) {
|
|
1902
|
+
_this.printLog("\u6062\u590D\u5F85\u53D1\u9001\u8BF7\u6C42\u5931\u8D25: " + e); // 如果解析失败,清除损坏的数据
|
|
1903
|
+
|
|
1904
|
+
|
|
1905
|
+
_this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, "[]");
|
|
1906
|
+
}
|
|
1907
|
+
};
|
|
1908
|
+
/**
|
|
1909
|
+
* 检查页面是否即将卸载
|
|
1910
|
+
* @returns 如果页面即将卸载返回 true,否则返回 false
|
|
1911
|
+
*/
|
|
1912
|
+
|
|
1913
|
+
|
|
1914
|
+
_this.isPageUnloading = function () {
|
|
1915
|
+
return document.visibilityState === "hidden";
|
|
1916
|
+
};
|
|
1917
|
+
/**
|
|
1918
|
+
* 使用 sendBeacon 发送数据(页面卸载时的备用方案)
|
|
1919
|
+
* @param params 数据参数
|
|
1920
|
+
* @param serverUrl 服务器地址
|
|
1921
|
+
* @param contentType 内容类型
|
|
1922
|
+
* @returns 是否发送成功
|
|
1923
|
+
*/
|
|
1924
|
+
|
|
1925
|
+
|
|
1926
|
+
_this.sendWithBeacon = function (params, serverUrl, contentType) {
|
|
1927
|
+
try {
|
|
1928
|
+
var blob = new Blob([JSON.stringify(params)], {
|
|
1929
|
+
type: contentType || "application/json"
|
|
1930
|
+
});
|
|
1931
|
+
return navigator.sendBeacon(serverUrl, blob);
|
|
1932
|
+
} catch (e) {
|
|
1933
|
+
if (_this.initConfig.showLog) {
|
|
1934
|
+
_this.printLog("sendBeacon \u53D1\u9001\u5931\u8D25: " + e);
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
return false;
|
|
1938
|
+
}
|
|
1939
|
+
};
|
|
1940
|
+
/**
|
|
1941
|
+
* 刷新待发送的单个请求(正常情况下的发送)
|
|
1942
|
+
* 注意:这个方法会直接发送,不会再次添加到 pendingRequests,避免循环
|
|
1943
|
+
*/
|
|
1944
|
+
|
|
1945
|
+
|
|
1946
|
+
_this.flushPendingRequests = function () {
|
|
1947
|
+
if (_this.pendingRequests.length === 0) {
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
var requestsToSend = __spreadArray([], _this.pendingRequests);
|
|
1952
|
+
|
|
1953
|
+
_this.pendingRequests = []; // 清除 LocalStorage 中的待发送请求
|
|
1954
|
+
|
|
1955
|
+
_this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, "[]"); // 尝试发送每个请求(使用 sendData,但如果失败不再添加到 pendingRequests,避免循环)
|
|
1956
|
+
|
|
1957
|
+
|
|
1958
|
+
requestsToSend.forEach(function (params) {
|
|
1959
|
+
// 直接调用 sendData,但不处理失败情况(避免循环)
|
|
1960
|
+
// 如果失败,数据会丢失,但这是可接受的,因为我们已经尝试过了
|
|
1961
|
+
_this.sendData(params).catch(function (err) {
|
|
1962
|
+
if (_this.initConfig.showLog) {
|
|
1963
|
+
_this.printLog("\u5F85\u53D1\u9001\u8BF7\u6C42\u53D1\u9001\u5931\u8D25\uFF08\u4E0D\u518D\u91CD\u8BD5\uFF09: " + err);
|
|
1964
|
+
}
|
|
1965
|
+
});
|
|
1966
|
+
});
|
|
1967
|
+
};
|
|
1828
1968
|
/**
|
|
1829
1969
|
* 保存批量队列到 LocalStorage
|
|
1830
1970
|
*/
|
|
@@ -1835,13 +1975,12 @@ function (_super) {
|
|
|
1835
1975
|
var queueString = JSON.stringify(_this.batchQueue); // 检查存储大小,避免超出 LocalStorage 限制(通常 5-10MB)
|
|
1836
1976
|
// 如果队列过大,只保留最新的数据
|
|
1837
1977
|
|
|
1838
|
-
if (queueString.length >
|
|
1839
|
-
// 4MB 限制
|
|
1978
|
+
if (queueString.length > _this.MAX_STORAGE_SIZE) {
|
|
1840
1979
|
var maxItems = Math.floor(_this.batchQueue.length * 0.8); // 保留 80%
|
|
1841
1980
|
|
|
1842
1981
|
_this.batchQueue = _this.batchQueue.slice(-maxItems);
|
|
1843
1982
|
|
|
1844
|
-
_this.printLog("\u961F\u5217\u8FC7\u5927\uFF0C\u5DF2\u622A\u65AD\u4FDD\u7559\u6700\u65B0 " + maxItems + " \u6761\u6570\u636E");
|
|
1983
|
+
_this.printLog("\u961F\u5217\u8FC7\u5927\uFF0C\u5DF2\u622A\u65AD\u4FDD\u7559\u6700\u65B0 " + maxItems + " \u6761\u6570\u636E\uFF08\u9650\u5236: " + _this.MAX_STORAGE_SIZE / 1024 / 1024 + "MB\uFF09");
|
|
1845
1984
|
}
|
|
1846
1985
|
|
|
1847
1986
|
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, JSON.stringify(_this.batchQueue));
|
|
@@ -1851,44 +1990,126 @@ function (_super) {
|
|
|
1851
1990
|
}
|
|
1852
1991
|
};
|
|
1853
1992
|
/**
|
|
1854
|
-
*
|
|
1993
|
+
* 设置页面卸载监听器,确保数据发送
|
|
1855
1994
|
*/
|
|
1856
1995
|
|
|
1857
1996
|
|
|
1858
1997
|
_this.setupBeforeUnloadListener = function () {
|
|
1859
|
-
//
|
|
1998
|
+
// 避免重复设置监听器
|
|
1999
|
+
if (_this.isUnloadListenerSetup) {
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
_this.isUnloadListenerSetup = true; // 使用 visibilitychange 事件(更可靠,支持页面跳转、切换标签页等场景)
|
|
2004
|
+
|
|
1860
2005
|
document.addEventListener("visibilitychange", function () {
|
|
1861
|
-
if (
|
|
1862
|
-
_this.
|
|
2006
|
+
if (_this.isPageUnloading()) {
|
|
2007
|
+
_this.flushPendingData();
|
|
1863
2008
|
}
|
|
1864
|
-
}); // 使用 beforeunload
|
|
2009
|
+
}); // 使用 beforeunload 事件作为备用(页面关闭/刷新)
|
|
1865
2010
|
|
|
1866
2011
|
window.addEventListener("beforeunload", function () {
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
navigator.sendBeacon(_this.initConfig.serverUrl, blob); // 如果 sendBeacon 成功,清除队列
|
|
2012
|
+
_this.flushPendingData();
|
|
2013
|
+
}); // 使用 pagehide 事件(更可靠,支持移动端)
|
|
2014
|
+
|
|
2015
|
+
window.addEventListener("pagehide", function () {
|
|
2016
|
+
_this.flushPendingData();
|
|
2017
|
+
});
|
|
2018
|
+
};
|
|
2019
|
+
/**
|
|
2020
|
+
* 刷新待发送数据(在页面卸载/跳转时调用)
|
|
2021
|
+
*/
|
|
1878
2022
|
|
|
1879
|
-
_this.batchQueue = [];
|
|
1880
2023
|
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
2024
|
+
_this.flushPendingData = function () {
|
|
2025
|
+
// 收集所有待发送的数据
|
|
2026
|
+
var allPendingData = []; // 如果有批量队列,添加到待发送列表
|
|
2027
|
+
|
|
2028
|
+
if (_this.batchQueue.length > 0) {
|
|
2029
|
+
allPendingData.push.apply(allPendingData, _this.batchQueue);
|
|
2030
|
+
} // 如果有待发送的单个请求,也添加到列表
|
|
2031
|
+
|
|
2032
|
+
|
|
2033
|
+
if (_this.pendingRequests.length > 0) {
|
|
2034
|
+
allPendingData.push.apply(allPendingData, _this.pendingRequests);
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
if (allPendingData.length === 0) {
|
|
2038
|
+
return;
|
|
2039
|
+
} // 使用 sendBeacon 发送数据(最可靠的方式)
|
|
2040
|
+
|
|
2041
|
+
|
|
2042
|
+
if (navigator.sendBeacon && _this.initConfig.serverUrl) {
|
|
2043
|
+
try {
|
|
2044
|
+
// 如果只有一条数据,直接发送;否则批量发送
|
|
2045
|
+
var dataToSend = allPendingData.length === 1 ? allPendingData[0] : {
|
|
2046
|
+
events: allPendingData
|
|
2047
|
+
};
|
|
2048
|
+
var blob = new Blob([JSON.stringify(dataToSend)], {
|
|
2049
|
+
type: _this.initConfig.contentType || "application/json"
|
|
2050
|
+
});
|
|
2051
|
+
var sent = navigator.sendBeacon(_this.initConfig.serverUrl, blob);
|
|
2052
|
+
|
|
2053
|
+
if (sent) {
|
|
2054
|
+
// 发送成功,清除所有队列
|
|
2055
|
+
_this.batchQueue = [];
|
|
2056
|
+
_this.pendingRequests = [];
|
|
2057
|
+
|
|
2058
|
+
_this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
|
|
2059
|
+
|
|
2060
|
+
if (_this.initConfig.showLog) {
|
|
2061
|
+
_this.printLog("\u9875\u9762\u5378\u8F7D\u65F6\u6210\u529F\u53D1\u9001 " + allPendingData.length + " \u6761\u6570\u636E");
|
|
1885
2062
|
}
|
|
1886
2063
|
} else {
|
|
1887
|
-
//
|
|
2064
|
+
// sendBeacon 返回 false,保存到 LocalStorage(批量模式)
|
|
2065
|
+
if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
|
|
2066
|
+
_this.saveBatchQueueToStorage();
|
|
2067
|
+
} // 保存 pendingRequests 到 LocalStorage(如果支持)
|
|
2068
|
+
|
|
2069
|
+
|
|
2070
|
+
if (_this.pendingRequests.length > 0) {
|
|
2071
|
+
try {
|
|
2072
|
+
_this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
|
|
2073
|
+
} catch (e) {
|
|
2074
|
+
// LocalStorage 可能已满或不可用
|
|
2075
|
+
if (_this.initConfig.showLog) {
|
|
2076
|
+
_this.printLog("\u4FDD\u5B58\u5F85\u53D1\u9001\u8BF7\u6C42\u5230 LocalStorage \u5931\u8D25: " + e);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
} catch (e) {
|
|
2082
|
+
// sendBeacon 失败,保存到 LocalStorage(批量模式)
|
|
2083
|
+
if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
|
|
1888
2084
|
_this.saveBatchQueueToStorage();
|
|
2085
|
+
} // 保存 pendingRequests 到 LocalStorage(如果支持)
|
|
2086
|
+
|
|
2087
|
+
|
|
2088
|
+
if (_this.pendingRequests.length > 0) {
|
|
2089
|
+
try {
|
|
2090
|
+
_this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
|
|
2091
|
+
} catch (e) {// LocalStorage 可能已满或不可用
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
if (_this.initConfig.showLog) {
|
|
2096
|
+
_this.printLog("\u9875\u9762\u5378\u8F7D\u65F6\u53D1\u9001\u6570\u636E\u5931\u8D25: " + e);
|
|
1889
2097
|
}
|
|
1890
2098
|
}
|
|
1891
|
-
}
|
|
2099
|
+
} else {
|
|
2100
|
+
// 不支持 sendBeacon,保存到 LocalStorage(批量模式)
|
|
2101
|
+
if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
|
|
2102
|
+
_this.saveBatchQueueToStorage();
|
|
2103
|
+
} // 保存 pendingRequests 到 LocalStorage(如果支持)
|
|
2104
|
+
|
|
2105
|
+
|
|
2106
|
+
if (_this.pendingRequests.length > 0) {
|
|
2107
|
+
try {
|
|
2108
|
+
_this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
|
|
2109
|
+
} catch (e) {// LocalStorage 可能已满或不可用
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
1892
2113
|
};
|
|
1893
2114
|
/**
|
|
1894
2115
|
* 发送数据通用函数
|
|
@@ -1920,16 +2141,61 @@ function (_super) {
|
|
|
1920
2141
|
success: true,
|
|
1921
2142
|
message: "已添加到批量队列"
|
|
1922
2143
|
});
|
|
1923
|
-
}
|
|
2144
|
+
} // 如果使用 sendBeacon 且没有自定义 header
|
|
2145
|
+
|
|
1924
2146
|
|
|
1925
2147
|
if (_this.isSupportBeaconSend() === true && !header && !initHeader) {
|
|
2148
|
+
// 检查页面是否即将卸载,如果是,直接使用 sendBeacon 发送,避免被取消
|
|
2149
|
+
if (_this.isPageUnloading()) {
|
|
2150
|
+
var sent = _this.sendWithBeacon(params, serverUrl, contentType);
|
|
2151
|
+
|
|
2152
|
+
if (sent) {
|
|
2153
|
+
return Promise.resolve({
|
|
2154
|
+
success: true,
|
|
2155
|
+
message: "页面卸载时发送成功"
|
|
2156
|
+
});
|
|
2157
|
+
} else {
|
|
2158
|
+
// sendBeacon 返回 false,添加到待发送队列
|
|
2159
|
+
_this.addToPendingRequests(params);
|
|
2160
|
+
|
|
2161
|
+
return Promise.resolve({
|
|
2162
|
+
success: true,
|
|
2163
|
+
message: "已添加到待发送队列"
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
} // 正常情况使用 sendBeacon
|
|
2167
|
+
|
|
2168
|
+
|
|
1926
2169
|
return _this.sendBeacon({
|
|
1927
2170
|
contentType: contentType,
|
|
1928
2171
|
url: serverUrl,
|
|
1929
2172
|
data: params
|
|
2173
|
+
}).catch(function (err) {
|
|
2174
|
+
// sendBeacon 失败,添加到待发送队列,避免数据丢失
|
|
2175
|
+
_this.addToPendingRequests(params);
|
|
2176
|
+
|
|
2177
|
+
return Promise.resolve({
|
|
2178
|
+
success: true,
|
|
2179
|
+
message: "sendBeacon 失败,已添加到待发送队列"
|
|
2180
|
+
});
|
|
1930
2181
|
});
|
|
1931
2182
|
} else {
|
|
2183
|
+
// 使用 XMLHttpRequest 发送
|
|
1932
2184
|
return new Promise(function (resolve, reject) {
|
|
2185
|
+
// 如果页面即将卸载,也尝试使用 sendBeacon 作为备用
|
|
2186
|
+
if (_this.isPageUnloading() && _this.isSupportBeaconSend() && !header && !initHeader) {
|
|
2187
|
+
var sent = _this.sendWithBeacon(params, serverUrl, contentType);
|
|
2188
|
+
|
|
2189
|
+
if (sent) {
|
|
2190
|
+
resolve({
|
|
2191
|
+
success: true,
|
|
2192
|
+
message: "页面卸载时使用 sendBeacon 发送成功"
|
|
2193
|
+
});
|
|
2194
|
+
return;
|
|
2195
|
+
} // sendBeacon 失败,继续使用 XMLHttpRequest
|
|
2196
|
+
|
|
2197
|
+
}
|
|
2198
|
+
|
|
1933
2199
|
_this.ajax({
|
|
1934
2200
|
header: header || initHeader,
|
|
1935
2201
|
url: serverUrl,
|
|
@@ -1946,7 +2212,20 @@ function (_super) {
|
|
|
1946
2212
|
});
|
|
1947
2213
|
},
|
|
1948
2214
|
error: function error(err, status) {
|
|
1949
|
-
|
|
2215
|
+
// 如果请求失败且页面即将卸载,尝试使用 sendBeacon
|
|
2216
|
+
if (_this.isPageUnloading() && _this.isSupportBeaconSend() && !header && !initHeader) {
|
|
2217
|
+
var sent = _this.sendWithBeacon(params, serverUrl, contentType);
|
|
2218
|
+
|
|
2219
|
+
if (sent) {
|
|
2220
|
+
resolve({
|
|
2221
|
+
success: true,
|
|
2222
|
+
message: "XMLHttpRequest 失败,已使用 sendBeacon 发送"
|
|
2223
|
+
});
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
reject({
|
|
1950
2229
|
success: false,
|
|
1951
2230
|
message: String(err),
|
|
1952
2231
|
code: status
|
|
@@ -2017,7 +2296,9 @@ function (_super) {
|
|
|
2017
2296
|
sampleRate: 1,
|
|
2018
2297
|
batchSend: false,
|
|
2019
2298
|
batchInterval: 5000,
|
|
2020
|
-
batchMaxSize: 10
|
|
2299
|
+
batchMaxSize: 10,
|
|
2300
|
+
trackPartKeyClick: false,
|
|
2301
|
+
pendingRequestsMaxSize: 50 // 待发送请求队列最大数量(防止内存溢出)
|
|
2021
2302
|
|
|
2022
2303
|
}; // 系统信息
|
|
2023
2304
|
|
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.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;
|
|
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,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e}function r(e){return(r="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 i=new(function(r){function i(){var e=r.call(this)||this;return e.batchQueue=[],e.batchTimer=null,e.BATCH_QUEUE_STORAGE_KEY="web_tracking_batch_queue",e.useCustomPageKey=!1,e.pendingRequests=[],e.isUnloadListenerSetup=!1,e.PENDING_REQUESTS_STORAGE_KEY="web_tracking_pending_requests",e.DEFAULT_PENDING_REQUESTS_MAX_SIZE=50,e.MAX_STORAGE_SIZE=4194304,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(),t.userInfo&&e.isObject(t.userInfo)&&(e.userInfo=t.userInfo),e.setCookie("retainedStartTime",e.getTimeStamp()),e.initConfig.batchSend&&e.restoreBatchQueueFromStorage(),e.restorePendingRequestsFromStorage(),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.initConfig.trackPartKeyClick?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,s=e.getParams({desc:n,event:"CustomTrack",itemKey:e.getItemKey(i,r),privateParamMap:{business:o}});return e.sendData(s,a)},e.listener=function(){e.initConfig.autoTrack&&(e.initConfig.isTrackSinglePage&&(e.rewriteHistory(),e.addSinglePageEvent(e.onPageViewCallback)),e.each(["load","beforeunload"],(function(t){e.addEventListener(window,t,e.onPageViewCallback)}))),(e.initConfig.autoTrack||e.initConfig.trackPartKeyClick)&&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,s={id:o,nodeName:r.nodeName,className:a,position:i},c=e.getParams({event:"WebClick",desc:e.eventDescMap.WebClick,itemKey:e.getItemKey(r.dataset.partKey),privateParamMap:{targetEle:s,pointerType:t.pointerType,currentUrl:e.currentUrl,elementSelector:e.getDomSelector(r)||""}});return e.sendData(c)}},e.onPageViewCallback=function(t){var n,r;(e.pendingRequests.length>0||e.initConfig.batchSend&&e.batchQueue.length>0)&&e.flushPendingData();var 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,s=e.initConfig.business,c=window.innerWidth,u=window.innerHeight,g=window.screen.width,l=window.screen.height,d=e.filterSensitiveData(s||{}),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:c,pageHeight:u,screenWidth:g,screenHeight:l,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=n([],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.addToPendingRequests=function(t){e.pendingRequests.push(t);var n=e.initConfig.pendingRequestsMaxSize||e.DEFAULT_PENDING_REQUESTS_MAX_SIZE;e.pendingRequests.length>n&&(e.pendingRequests=e.pendingRequests.slice(-n),e.initConfig.showLog&&e.printLog("待发送请求队列已满,已移除最旧的数据(最大限制: "+n+")"))},e.restorePendingRequestsFromStorage=function(){try{var t=e.getLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY);if(t){var n=JSON.parse(t);Array.isArray(n)&&n.length>0&&(e.pendingRequests=n,e.initConfig.showLog&&e.printLog("从 LocalStorage 恢复 "+n.length+" 条待发送请求"),e.pendingRequests.length>0&&e.flushPendingRequests())}}catch(t){e.printLog("恢复待发送请求失败: "+t),e.setLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY,"[]")}},e.isPageUnloading=function(){return"hidden"===document.visibilityState},e.sendWithBeacon=function(t,n,r){try{var i=new Blob([JSON.stringify(t)],{type:r||"application/json"});return navigator.sendBeacon(n,i)}catch(t){return e.initConfig.showLog&&e.printLog("sendBeacon 发送失败: "+t),!1}},e.flushPendingRequests=function(){if(0!==e.pendingRequests.length){var t=n([],e.pendingRequests);e.pendingRequests=[],e.setLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY,"[]"),t.forEach((function(t){e.sendData(t).catch((function(t){e.initConfig.showLog&&e.printLog("待发送请求发送失败(不再重试): "+t)}))}))}},e.saveBatchQueueToStorage=function(){try{if(JSON.stringify(e.batchQueue).length>e.MAX_STORAGE_SIZE){var t=Math.floor(.8*e.batchQueue.length);e.batchQueue=e.batchQueue.slice(-t),e.printLog("队列过大,已截断保留最新 "+t+" 条数据(限制: "+e.MAX_STORAGE_SIZE/1024/1024+"MB)")}e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,JSON.stringify(e.batchQueue))}catch(t){e.printLog("保存批量队列到 LocalStorage 失败: "+t)}},e.setupBeforeUnloadListener=function(){e.isUnloadListenerSetup||(e.isUnloadListenerSetup=!0,document.addEventListener("visibilitychange",(function(){e.isPageUnloading()&&e.flushPendingData()})),window.addEventListener("beforeunload",(function(){e.flushPendingData()})),window.addEventListener("pagehide",(function(){e.flushPendingData()})))},e.flushPendingData=function(){var t=[];if(e.batchQueue.length>0&&t.push.apply(t,e.batchQueue),e.pendingRequests.length>0&&t.push.apply(t,e.pendingRequests),0!==t.length)if(navigator.sendBeacon&&e.initConfig.serverUrl)try{var n=1===t.length?t[0]:{events:t},r=new Blob([JSON.stringify(n)],{type:e.initConfig.contentType||"application/json"});if(navigator.sendBeacon(e.initConfig.serverUrl,r))e.batchQueue=[],e.pendingRequests=[],e.setLocalStorage(e.BATCH_QUEUE_STORAGE_KEY,"[]"),e.initConfig.showLog&&e.printLog("页面卸载时成功发送 "+t.length+" 条数据");else if(e.initConfig.batchSend&&e.batchQueue.length>0&&e.saveBatchQueueToStorage(),e.pendingRequests.length>0)try{e.setLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY,JSON.stringify(e.pendingRequests))}catch(t){e.initConfig.showLog&&e.printLog("保存待发送请求到 LocalStorage 失败: "+t)}}catch(t){if(e.initConfig.batchSend&&e.batchQueue.length>0&&e.saveBatchQueueToStorage(),e.pendingRequests.length>0)try{e.setLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY,JSON.stringify(e.pendingRequests))}catch(e){}e.initConfig.showLog&&e.printLog("页面卸载时发送数据失败: "+t)}else if(e.initConfig.batchSend&&e.batchQueue.length>0&&e.saveBatchQueueToStorage(),e.pendingRequests.length>0)try{e.setLocalStorage(e.PENDING_REQUESTS_STORAGE_KEY,JSON.stringify(e.pendingRequests))}catch(e){}},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,s=r.showLog,c=r.header,u=r.batchSend;return s&&e.printLog(t),u?(e.addToBatchQueue(t),Promise.resolve({success:!0,message:"已添加到批量队列"})):!0!==e.isSupportBeaconSend()||n||c?new Promise((function(r,s){if(e.isPageUnloading()&&e.isSupportBeaconSend()&&!n&&!c&&e.sendWithBeacon(t,i,a))return void r({success:!0,message:"页面卸载时使用 sendBeacon 发送成功"});e.ajax({header:n||c,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(o,u){if(e.isPageUnloading()&&e.isSupportBeaconSend()&&!n&&!c&&e.sendWithBeacon(t,i,a))return void r({success:!0,message:"XMLHttpRequest 失败,已使用 sendBeacon 发送"});s({success:!1,message:String(o),code:u})}})})):e.isPageUnloading()?e.sendWithBeacon(t,i,a)?Promise.resolve({success:!0,message:"页面卸载时发送成功"}):(e.addToPendingRequests(t),Promise.resolve({success:!0,message:"已添加到待发送队列"})):e.sendBeacon({contentType:a,url:i,data:t}).catch((function(n){return e.addToPendingRequests(t),Promise.resolve({success:!0,message:"sendBeacon 失败,已添加到待发送队列"})}))},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,trackPartKeyClick:!1,pendingRequestsMaxSize:50},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)}(i,r),i.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)}))},i}(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,s=t.match(/(ipod).*\s([\d_]+)/i),c=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),g=t.match(/(android)\s([\d\.]+)/i),l=t.match(/(Windows NT)\s([\d\.]+)/i),d=t.match(/(Mac OS X)\s([\d_]+)/i);r=[],g?(r.push("Android "+g[2]),n="h5"):u?(r.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):c?(r.push("iPad, iOS "+c[2].replace(/_/g,".")),n="ipad"):s?(r.push("iPod, iOS "+s[2].replace(/_/g,".")),n="h5"):l?(r.push("Windows "+l[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 s(e){return e||!1}var c="",u="",g="";e&&(c=s(e)),t&&(u=s(t)),r&&(g=s(r)),c&&u&&(document.cookie=c+"="+encodeURIComponent(u)+i+"; path=/"+g)},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 n(e){if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return"object"===r(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,s=t.error;t.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},t.error=function(e,t){s&&s(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(n(i.responseText)):t.error&&t.error(n(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":r(navigator))||"function"!=typeof navigator.sendBeacon)return t;var n=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===n.safari&&(n.safari=Number(o[0])),o[0]&&+o[0]<13?(n.chrome>41||n.firefox>30||n.opera>25||n.safari>12)&&(t=!0):(n.chrome>41||n.firefox>30||n.opera>25||n.safari>11.3)&&(t=!0)}else(n.chrome>38||n.edge>13||n.firefox>30||n.opera>25||n.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(),s=t-(a-r);s<=0||s>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)}),s))}},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":r(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("."),s=e+"=12345;domain=."+a;if(document.cookie=s,t.test(document.cookie))return document.cookie=s+";expires="+n,a}return r},e}()));export default i;
|