|
@@ -44,17 +44,49 @@ class Tracker {
|
|
|
this.timer = null;
|
|
|
this.startTime = 0;
|
|
|
this.heartbeatInterval = options.heartbeatInterval || 30000; // 默认30秒发送一次心跳
|
|
|
+ this.visitCookieTimeout = options.visitCookieTimeout || 1; // 默认访问次数cookie有效期1分钟
|
|
|
+ this.maxVisitCount = options.maxVisitCount || 5; // 默认最大访问次数5次
|
|
|
+ this.blockCookieTimeout = options.blockCookieTimeout || 180; // 默认封锁cookie有效期180分钟
|
|
|
+ this.myEventSend = options.myEventSend || (() => {}); // 是否开启自定义事件上报
|
|
|
+ this.beforeDestroy = options.beforeDestroy || (() => {}); // 销毁前的回调函数
|
|
|
}
|
|
|
|
|
|
- init() {
|
|
|
+init() {
|
|
|
+ const visitCookieName = 'userVisitCount';
|
|
|
+ const blockCookieName = 'userBlocked';
|
|
|
+ const isBlocked = getCookie(blockCookieName);
|
|
|
+ const doneFN = () => {
|
|
|
this.startTime = Date.now();
|
|
|
this.bindEvents();
|
|
|
this.startHeartbeat();
|
|
|
}
|
|
|
+ if (isBlocked) {
|
|
|
+ // restoreBlock();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ let visitCount = getCookie(visitCookieName);
|
|
|
+ if (visitCount) {
|
|
|
+ visitCount = parseInt(visitCount, 10);
|
|
|
+ if (visitCount >= this.maxVisitCount) {
|
|
|
+ setCookie(blockCookieName, 'true', this.blockCookieTimeout); // 封锁用户 180 分钟
|
|
|
+ deleteCookie(visitCookieName);
|
|
|
+ // restoreBlock();
|
|
|
+ } else {
|
|
|
+ visitCount += 1;
|
|
|
+ setCookie(visitCookieName, visitCount, this.visitCookieTimeout); // 每次访问 +1,有效期 1 分钟
|
|
|
+ doneFN();
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ setCookie(visitCookieName, '1', this.visitCookieTimeout); // 首次访问,设置访问次数为 1
|
|
|
+ doneFN();
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
bindEvents() {
|
|
|
window.addEventListener('beforeunload', this.handleBeforeUnload);
|
|
|
window.addEventListener('click', this.handleClickEvent);
|
|
|
+ this.myEventSend(this.sendData.bind(this)); // 绑定自定义事件上报
|
|
|
}
|
|
|
|
|
|
startHeartbeat() {
|
|
@@ -103,6 +135,7 @@ class Tracker {
|
|
|
destroy() {
|
|
|
window.removeEventListener('beforeunload', this.handleBeforeUnload);
|
|
|
window.removeEventListener('click', this.handleClickEvent);
|
|
|
+ this.beforeDestroy();
|
|
|
if (this.timer) {
|
|
|
clearInterval(this.timer);
|
|
|
}
|