stayEvent.ts 2.33 KB
/*
 * @Author: yangming yangming@didihu.com.cn
 * @Date: 2023-11-30 14:46:13
 * @LastEditors: yangming yangming@didihu.com.cn
 * @LastEditTime: 2023-12-15 16:49:25
 * @FilePath: \glsx-tracker-javascript\src\modules\stayEvent.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
console.log(222)
import type { StayDescriptor } from '../types/stay'
import collect from './collect'
import Events from './events'
class StayEvent {
  static instance: StayEvent | undefined
  _options: any
  start_time: number = Date.now()
  timeout_time: number = 1000
  timer: NodeJS.Timeout | undefined
  interval_time: number = 5000
  constructor() {
    console.log(1111111)
  }
  /**
   * 获取视口位置
   */
  getPosition(): number {
    let position = document.documentElement.scrollTop || document.body.scrollTop
    return +position.toFixed(2)
  }
  /**
   * 获取停留时间
   */
  getStayTime(): number {
    let duration = (Date.now() - this.start_time) / 1000
    if (duration < 0) {
      duration = 0
    }
    return +duration.toFixed(2)
  }
  /**
   * 获取停留事件的数据
   */
  getStayInfo(): StayDescriptor {
    const position = this.getPosition()
    const duration = this.getStayTime()
    return {
      position,
      duration
    }
  }
  /**
   * 开启监听停留事件
   * params
   */
  trigger(this: StayEvent) {
    Events.addEvent(window, 'scroll', (e: MouseEvent) => {
      if (this._options.collect_url && !this._options.collect_url()) {
        return false
      }
      if (Date.now() - this.start_time < this._options.delay_time) {
        return false
      }
      if (!this.timer) {
        const para = this.getStayInfo()
        this.timer = setTimeout(() => {
          this.send(para)
        }, this.timeout_time)
      }
    })
  }
  /**
   * 发送数据
   */
  send(para: object) {
    this.timer = undefined
    this.start_time = Date.now()
    collect.getStayEvent(para)
  }
  /**
   * 初始化
   * params data初始化数据
   */
  init<T>(data: T) {
    this._options = data
    this.trigger()
  }
  /**
   * 单例模式
   */
  static getInstance() {
    if (!StayEvent.instance) {
      StayEvent.instance = new StayEvent()
    }
    return StayEvent.instance
  }
}
export default new StayEvent()