@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.js CHANGED
@@ -1254,7 +1254,17 @@
1254
1254
 
1255
1255
  _this.BATCH_QUEUE_STORAGE_KEY = "web_tracking_batch_queue"; // 是否使用自定义 pageKey(如果为 true,路由变化时不会自动更新 pageKey)
1256
1256
 
1257
- _this.useCustomPageKey = false; // 用户信息
1257
+ _this.useCustomPageKey = false; // 待发送的单个请求队列(用于页面跳转时发送)
1258
+
1259
+ _this.pendingRequests = []; // 页面卸载监听器是否已设置
1260
+
1261
+ _this.isUnloadListenerSetup = false; // LocalStorage 存储 key(待发送请求)
1262
+
1263
+ _this.PENDING_REQUESTS_STORAGE_KEY = "web_tracking_pending_requests"; // 待发送请求队列最大大小(默认值,可通过配置覆盖)
1264
+
1265
+ _this.DEFAULT_PENDING_REQUESTS_MAX_SIZE = 50; // LocalStorage 最大大小限制(4MB)
1266
+
1267
+ _this.MAX_STORAGE_SIZE = 4 * 1024 * 1024; // 用户信息
1258
1268
 
1259
1269
  _this.userInfo = null; // 当前路由
1260
1270
 
@@ -1291,17 +1301,24 @@
1291
1301
 
1292
1302
  _this.systemsInfo = _this.getSystemsInfo(initParams.platform); // 获取设备ID
1293
1303
 
1294
- _this.deviceId = _this.getDeviceId();
1304
+ _this.deviceId = _this.getDeviceId(); // 如果传入了 userInfo,设置用户信息
1305
+
1306
+ if (initParams.userInfo && _this.isObject(initParams.userInfo)) {
1307
+ _this.userInfo = initParams.userInfo;
1308
+ }
1295
1309
 
1296
1310
  _this.setCookie("retainedStartTime", _this.getTimeStamp()); // 如果启用了批量发送,从 LocalStorage 恢复队列
1297
1311
 
1298
1312
 
1299
1313
  if (_this.initConfig.batchSend) {
1300
- _this.restoreBatchQueueFromStorage(); // 监听页面卸载事件,保存队列
1314
+ _this.restoreBatchQueueFromStorage();
1315
+ } // 恢复待发送的单个请求
1301
1316
 
1302
1317
 
1303
- _this.setupBeforeUnloadListener();
1304
- }
1318
+ _this.restorePendingRequestsFromStorage(); // 无论是否启用批量发送,都需要监听页面卸载事件,确保数据发送
1319
+
1320
+
1321
+ _this.setupBeforeUnloadListener();
1305
1322
  };
1306
1323
  /**
1307
1324
  * TODO: 需要判断有哪些不能被预制的参数
@@ -1340,10 +1357,10 @@
1340
1357
  _this.printLog("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!");
1341
1358
 
1342
1359
  _this.initConfig["showLog"] = true;
1343
- } // 如果启用了全埋点
1360
+ } // 如果启用了全埋点或启用了 data-part-key 点击追踪
1344
1361
 
1345
1362
 
1346
- if (!!_this.initConfig["autoTrack"]) {
1363
+ if (!!_this.initConfig["autoTrack"] || !!_this.initConfig["trackPartKeyClick"]) {
1347
1364
  // 启用监听
1348
1365
  _this.listener();
1349
1366
  } else {
@@ -1443,17 +1460,23 @@
1443
1460
 
1444
1461
 
1445
1462
  _this.listener = function () {
1446
- if (!!_this.initConfig.isTrackSinglePage) {
1447
- _this.rewriteHistory();
1463
+ // 如果启用了全埋点,监听页面浏览事件
1464
+ if (!!_this.initConfig.autoTrack) {
1465
+ if (!!_this.initConfig.isTrackSinglePage) {
1466
+ _this.rewriteHistory();
1448
1467
 
1449
- _this.addSinglePageEvent(_this.onPageViewCallback);
1450
- }
1468
+ _this.addSinglePageEvent(_this.onPageViewCallback);
1469
+ }
1470
+
1471
+ _this.each(["load", "beforeunload"], function (historyType) {
1472
+ _this.addEventListener(window, historyType, _this.onPageViewCallback);
1473
+ });
1474
+ } // 如果启用了全埋点或启用了 data-part-key 点击追踪,监听点击事件
1451
1475
 
1452
- _this.each(["load", "beforeunload"], function (historyType) {
1453
- _this.addEventListener(window, historyType, _this.onPageViewCallback);
1454
- });
1455
1476
 
1456
- _this.addEventListener(window, "click", _this.onClickCallback);
1477
+ if (!!_this.initConfig.autoTrack || !!_this.initConfig.trackPartKeyClick) {
1478
+ _this.addEventListener(window, "click", _this.onClickCallback);
1479
+ }
1457
1480
  };
1458
1481
  /**
1459
1482
  * @description 取消全埋点事件
@@ -1580,7 +1603,12 @@
1580
1603
 
1581
1604
 
1582
1605
  _this.onPageViewCallback = function (e) {
1583
- var _a, _b;
1606
+ var _a, _b; // 在路由变化前,先发送待发送的数据(避免被取消)
1607
+
1608
+
1609
+ if (_this.pendingRequests.length > 0 || _this.initConfig.batchSend && _this.batchQueue.length > 0) {
1610
+ _this.flushPendingData();
1611
+ }
1584
1612
 
1585
1613
  var ORGIN = window.location.origin;
1586
1614
 
@@ -1831,6 +1859,118 @@
1831
1859
  _this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
1832
1860
  }
1833
1861
  };
1862
+ /**
1863
+ * 添加到待发送请求队列
1864
+ * @param params 数据参数
1865
+ */
1866
+
1867
+
1868
+ _this.addToPendingRequests = function (params) {
1869
+ _this.pendingRequests.push(params); // 限制队列大小,防止内存溢出
1870
+
1871
+
1872
+ var maxSize = _this.initConfig.pendingRequestsMaxSize || _this.DEFAULT_PENDING_REQUESTS_MAX_SIZE;
1873
+
1874
+ if (_this.pendingRequests.length > maxSize) {
1875
+ _this.pendingRequests = _this.pendingRequests.slice(-maxSize);
1876
+
1877
+ if (_this.initConfig.showLog) {
1878
+ _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");
1879
+ }
1880
+ }
1881
+ };
1882
+ /**
1883
+ * 从 LocalStorage 恢复待发送请求
1884
+ */
1885
+
1886
+
1887
+ _this.restorePendingRequestsFromStorage = function () {
1888
+ try {
1889
+ var storedRequests = _this.getLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY);
1890
+
1891
+ if (storedRequests) {
1892
+ var parsedRequests = JSON.parse(storedRequests);
1893
+
1894
+ if (Array.isArray(parsedRequests) && parsedRequests.length > 0) {
1895
+ _this.pendingRequests = parsedRequests;
1896
+
1897
+ if (_this.initConfig.showLog) {
1898
+ _this.printLog("\u4ECE LocalStorage \u6062\u590D " + parsedRequests.length + " \u6761\u5F85\u53D1\u9001\u8BF7\u6C42");
1899
+ } // 恢复后立即尝试发送
1900
+
1901
+
1902
+ if (_this.pendingRequests.length > 0) {
1903
+ _this.flushPendingRequests();
1904
+ }
1905
+ }
1906
+ }
1907
+ } catch (e) {
1908
+ _this.printLog("\u6062\u590D\u5F85\u53D1\u9001\u8BF7\u6C42\u5931\u8D25: " + e); // 如果解析失败,清除损坏的数据
1909
+
1910
+
1911
+ _this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, "[]");
1912
+ }
1913
+ };
1914
+ /**
1915
+ * 检查页面是否即将卸载
1916
+ * @returns 如果页面即将卸载返回 true,否则返回 false
1917
+ */
1918
+
1919
+
1920
+ _this.isPageUnloading = function () {
1921
+ return document.visibilityState === "hidden";
1922
+ };
1923
+ /**
1924
+ * 使用 sendBeacon 发送数据(页面卸载时的备用方案)
1925
+ * @param params 数据参数
1926
+ * @param serverUrl 服务器地址
1927
+ * @param contentType 内容类型
1928
+ * @returns 是否发送成功
1929
+ */
1930
+
1931
+
1932
+ _this.sendWithBeacon = function (params, serverUrl, contentType) {
1933
+ try {
1934
+ var blob = new Blob([JSON.stringify(params)], {
1935
+ type: contentType || "application/json"
1936
+ });
1937
+ return navigator.sendBeacon(serverUrl, blob);
1938
+ } catch (e) {
1939
+ if (_this.initConfig.showLog) {
1940
+ _this.printLog("sendBeacon \u53D1\u9001\u5931\u8D25: " + e);
1941
+ }
1942
+
1943
+ return false;
1944
+ }
1945
+ };
1946
+ /**
1947
+ * 刷新待发送的单个请求(正常情况下的发送)
1948
+ * 注意:这个方法会直接发送,不会再次添加到 pendingRequests,避免循环
1949
+ */
1950
+
1951
+
1952
+ _this.flushPendingRequests = function () {
1953
+ if (_this.pendingRequests.length === 0) {
1954
+ return;
1955
+ }
1956
+
1957
+ var requestsToSend = __spreadArray([], _this.pendingRequests);
1958
+
1959
+ _this.pendingRequests = []; // 清除 LocalStorage 中的待发送请求
1960
+
1961
+ _this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, "[]"); // 尝试发送每个请求(使用 sendData,但如果失败不再添加到 pendingRequests,避免循环)
1962
+
1963
+
1964
+ requestsToSend.forEach(function (params) {
1965
+ // 直接调用 sendData,但不处理失败情况(避免循环)
1966
+ // 如果失败,数据会丢失,但这是可接受的,因为我们已经尝试过了
1967
+ _this.sendData(params).catch(function (err) {
1968
+ if (_this.initConfig.showLog) {
1969
+ _this.printLog("\u5F85\u53D1\u9001\u8BF7\u6C42\u53D1\u9001\u5931\u8D25\uFF08\u4E0D\u518D\u91CD\u8BD5\uFF09: " + err);
1970
+ }
1971
+ });
1972
+ });
1973
+ };
1834
1974
  /**
1835
1975
  * 保存批量队列到 LocalStorage
1836
1976
  */
@@ -1841,13 +1981,12 @@
1841
1981
  var queueString = JSON.stringify(_this.batchQueue); // 检查存储大小,避免超出 LocalStorage 限制(通常 5-10MB)
1842
1982
  // 如果队列过大,只保留最新的数据
1843
1983
 
1844
- if (queueString.length > 4 * 1024 * 1024) {
1845
- // 4MB 限制
1984
+ if (queueString.length > _this.MAX_STORAGE_SIZE) {
1846
1985
  var maxItems = Math.floor(_this.batchQueue.length * 0.8); // 保留 80%
1847
1986
 
1848
1987
  _this.batchQueue = _this.batchQueue.slice(-maxItems);
1849
1988
 
1850
- _this.printLog("\u961F\u5217\u8FC7\u5927\uFF0C\u5DF2\u622A\u65AD\u4FDD\u7559\u6700\u65B0 " + maxItems + " \u6761\u6570\u636E");
1989
+ _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");
1851
1990
  }
1852
1991
 
1853
1992
  _this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, JSON.stringify(_this.batchQueue));
@@ -1857,44 +1996,126 @@
1857
1996
  }
1858
1997
  };
1859
1998
  /**
1860
- * 设置页面卸载监听器,保存队列
1999
+ * 设置页面卸载监听器,确保数据发送
1861
2000
  */
1862
2001
 
1863
2002
 
1864
2003
  _this.setupBeforeUnloadListener = function () {
1865
- // 使用 visibilitychange 事件(更可靠)
2004
+ // 避免重复设置监听器
2005
+ if (_this.isUnloadListenerSetup) {
2006
+ return;
2007
+ }
2008
+
2009
+ _this.isUnloadListenerSetup = true; // 使用 visibilitychange 事件(更可靠,支持页面跳转、切换标签页等场景)
2010
+
1866
2011
  document.addEventListener("visibilitychange", function () {
1867
- if (document.visibilityState === "hidden" && _this.batchQueue.length > 0) {
1868
- _this.saveBatchQueueToStorage();
2012
+ if (_this.isPageUnloading()) {
2013
+ _this.flushPendingData();
1869
2014
  }
1870
- }); // 使用 beforeunload 事件作为备用
2015
+ }); // 使用 beforeunload 事件作为备用(页面关闭/刷新)
1871
2016
 
1872
2017
  window.addEventListener("beforeunload", function () {
1873
- if (_this.batchQueue.length > 0) {
1874
- // 使用 sendBeacon 尝试发送数据(如果支持)
1875
- if (navigator.sendBeacon && _this.initConfig.serverUrl) {
1876
- try {
1877
- var data = JSON.stringify({
1878
- events: _this.batchQueue
1879
- });
1880
- var blob = new Blob([data], {
1881
- type: "application/json"
1882
- });
1883
- navigator.sendBeacon(_this.initConfig.serverUrl, blob); // 如果 sendBeacon 成功,清除队列
2018
+ _this.flushPendingData();
2019
+ }); // 使用 pagehide 事件(更可靠,支持移动端)
2020
+
2021
+ window.addEventListener("pagehide", function () {
2022
+ _this.flushPendingData();
2023
+ });
2024
+ };
2025
+ /**
2026
+ * 刷新待发送数据(在页面卸载/跳转时调用)
2027
+ */
1884
2028
 
1885
- _this.batchQueue = [];
1886
2029
 
1887
- _this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
1888
- } catch (e) {
1889
- // sendBeacon 失败,保存到 LocalStorage
1890
- _this.saveBatchQueueToStorage();
2030
+ _this.flushPendingData = function () {
2031
+ // 收集所有待发送的数据
2032
+ var allPendingData = []; // 如果有批量队列,添加到待发送列表
2033
+
2034
+ if (_this.batchQueue.length > 0) {
2035
+ allPendingData.push.apply(allPendingData, _this.batchQueue);
2036
+ } // 如果有待发送的单个请求,也添加到列表
2037
+
2038
+
2039
+ if (_this.pendingRequests.length > 0) {
2040
+ allPendingData.push.apply(allPendingData, _this.pendingRequests);
2041
+ }
2042
+
2043
+ if (allPendingData.length === 0) {
2044
+ return;
2045
+ } // 使用 sendBeacon 发送数据(最可靠的方式)
2046
+
2047
+
2048
+ if (navigator.sendBeacon && _this.initConfig.serverUrl) {
2049
+ try {
2050
+ // 如果只有一条数据,直接发送;否则批量发送
2051
+ var dataToSend = allPendingData.length === 1 ? allPendingData[0] : {
2052
+ events: allPendingData
2053
+ };
2054
+ var blob = new Blob([JSON.stringify(dataToSend)], {
2055
+ type: _this.initConfig.contentType || "application/json"
2056
+ });
2057
+ var sent = navigator.sendBeacon(_this.initConfig.serverUrl, blob);
2058
+
2059
+ if (sent) {
2060
+ // 发送成功,清除所有队列
2061
+ _this.batchQueue = [];
2062
+ _this.pendingRequests = [];
2063
+
2064
+ _this.setLocalStorage(_this.BATCH_QUEUE_STORAGE_KEY, "[]");
2065
+
2066
+ if (_this.initConfig.showLog) {
2067
+ _this.printLog("\u9875\u9762\u5378\u8F7D\u65F6\u6210\u529F\u53D1\u9001 " + allPendingData.length + " \u6761\u6570\u636E");
1891
2068
  }
1892
2069
  } else {
1893
- // 不支持 sendBeacon,保存到 LocalStorage
2070
+ // sendBeacon 返回 false,保存到 LocalStorage(批量模式)
2071
+ if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
2072
+ _this.saveBatchQueueToStorage();
2073
+ } // 保存 pendingRequests 到 LocalStorage(如果支持)
2074
+
2075
+
2076
+ if (_this.pendingRequests.length > 0) {
2077
+ try {
2078
+ _this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
2079
+ } catch (e) {
2080
+ // LocalStorage 可能已满或不可用
2081
+ if (_this.initConfig.showLog) {
2082
+ _this.printLog("\u4FDD\u5B58\u5F85\u53D1\u9001\u8BF7\u6C42\u5230 LocalStorage \u5931\u8D25: " + e);
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ } catch (e) {
2088
+ // sendBeacon 失败,保存到 LocalStorage(批量模式)
2089
+ if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
1894
2090
  _this.saveBatchQueueToStorage();
2091
+ } // 保存 pendingRequests 到 LocalStorage(如果支持)
2092
+
2093
+
2094
+ if (_this.pendingRequests.length > 0) {
2095
+ try {
2096
+ _this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
2097
+ } catch (e) {// LocalStorage 可能已满或不可用
2098
+ }
2099
+ }
2100
+
2101
+ if (_this.initConfig.showLog) {
2102
+ _this.printLog("\u9875\u9762\u5378\u8F7D\u65F6\u53D1\u9001\u6570\u636E\u5931\u8D25: " + e);
1895
2103
  }
1896
2104
  }
1897
- });
2105
+ } else {
2106
+ // 不支持 sendBeacon,保存到 LocalStorage(批量模式)
2107
+ if (_this.initConfig.batchSend && _this.batchQueue.length > 0) {
2108
+ _this.saveBatchQueueToStorage();
2109
+ } // 保存 pendingRequests 到 LocalStorage(如果支持)
2110
+
2111
+
2112
+ if (_this.pendingRequests.length > 0) {
2113
+ try {
2114
+ _this.setLocalStorage(_this.PENDING_REQUESTS_STORAGE_KEY, JSON.stringify(_this.pendingRequests));
2115
+ } catch (e) {// LocalStorage 可能已满或不可用
2116
+ }
2117
+ }
2118
+ }
1898
2119
  };
1899
2120
  /**
1900
2121
  * 发送数据通用函数
@@ -1926,16 +2147,61 @@
1926
2147
  success: true,
1927
2148
  message: "已添加到批量队列"
1928
2149
  });
1929
- }
2150
+ } // 如果使用 sendBeacon 且没有自定义 header
2151
+
1930
2152
 
1931
2153
  if (_this.isSupportBeaconSend() === true && !header && !initHeader) {
2154
+ // 检查页面是否即将卸载,如果是,直接使用 sendBeacon 发送,避免被取消
2155
+ if (_this.isPageUnloading()) {
2156
+ var sent = _this.sendWithBeacon(params, serverUrl, contentType);
2157
+
2158
+ if (sent) {
2159
+ return Promise.resolve({
2160
+ success: true,
2161
+ message: "页面卸载时发送成功"
2162
+ });
2163
+ } else {
2164
+ // sendBeacon 返回 false,添加到待发送队列
2165
+ _this.addToPendingRequests(params);
2166
+
2167
+ return Promise.resolve({
2168
+ success: true,
2169
+ message: "已添加到待发送队列"
2170
+ });
2171
+ }
2172
+ } // 正常情况使用 sendBeacon
2173
+
2174
+
1932
2175
  return _this.sendBeacon({
1933
2176
  contentType: contentType,
1934
2177
  url: serverUrl,
1935
2178
  data: params
2179
+ }).catch(function (err) {
2180
+ // sendBeacon 失败,添加到待发送队列,避免数据丢失
2181
+ _this.addToPendingRequests(params);
2182
+
2183
+ return Promise.resolve({
2184
+ success: true,
2185
+ message: "sendBeacon 失败,已添加到待发送队列"
2186
+ });
1936
2187
  });
1937
2188
  } else {
2189
+ // 使用 XMLHttpRequest 发送
1938
2190
  return new Promise(function (resolve, reject) {
2191
+ // 如果页面即将卸载,也尝试使用 sendBeacon 作为备用
2192
+ if (_this.isPageUnloading() && _this.isSupportBeaconSend() && !header && !initHeader) {
2193
+ var sent = _this.sendWithBeacon(params, serverUrl, contentType);
2194
+
2195
+ if (sent) {
2196
+ resolve({
2197
+ success: true,
2198
+ message: "页面卸载时使用 sendBeacon 发送成功"
2199
+ });
2200
+ return;
2201
+ } // sendBeacon 失败,继续使用 XMLHttpRequest
2202
+
2203
+ }
2204
+
1939
2205
  _this.ajax({
1940
2206
  header: header || initHeader,
1941
2207
  url: serverUrl,
@@ -1952,7 +2218,20 @@
1952
2218
  });
1953
2219
  },
1954
2220
  error: function error(err, status) {
1955
- return reject({
2221
+ // 如果请求失败且页面即将卸载,尝试使用 sendBeacon
2222
+ if (_this.isPageUnloading() && _this.isSupportBeaconSend() && !header && !initHeader) {
2223
+ var sent = _this.sendWithBeacon(params, serverUrl, contentType);
2224
+
2225
+ if (sent) {
2226
+ resolve({
2227
+ success: true,
2228
+ message: "XMLHttpRequest 失败,已使用 sendBeacon 发送"
2229
+ });
2230
+ return;
2231
+ }
2232
+ }
2233
+
2234
+ reject({
1956
2235
  success: false,
1957
2236
  message: String(err),
1958
2237
  code: status
@@ -2023,7 +2302,9 @@
2023
2302
  sampleRate: 1,
2024
2303
  batchSend: false,
2025
2304
  batchInterval: 5000,
2026
- batchMaxSize: 10 // 批量发送最大数量
2305
+ batchMaxSize: 10,
2306
+ trackPartKeyClick: false,
2307
+ pendingRequestsMaxSize: 50 // 待发送请求队列最大数量(防止内存溢出)
2027
2308
 
2028
2309
  }; // 系统信息
2029
2310
 
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.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,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;"):""},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,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)}return 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,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;"):""},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}()))}));