viewEvent.ts 3.09 KB
/*
 * @Author: yangming yangming@didihu.com.cn
 * @Date: 2023-11-30 14:45:53
 * @LastEditors: yangming yangming@didihu.com.cn
 * @LastEditTime: 2023-12-21 09:25:12
 * @FilePath: \glsx-tracker-javascript\src\modules\viewEvent.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import type { viewBase, routerOption } from '../types/view'
import Events from './events'
import utils from '../utils/helper'
import collect from './collect'
class ViewEvent extends Events {
  baseParams: viewBase
  last_time: string
  routerModel: routerOption | undefined = 'hash'
  /**
   * 初始化页面信息
   *$page_title: 页面标题
    $page_url: 页面地址
    $page_path: 页面地址
    $path_href: 页面完整地址
    $enter_time: 进入页面的时间
    $leave_time:离开页面的时间
    $page_referrer: 页面来源
   */
  constructor() {
    super()
    this.last_time = utils.dateFormat(new Date())
    this.baseParams = {
      $page_title: document.title,
      $page_url: location.href,
      $page_path: location.pathname,
      $enter_time: this.last_time,
      $leave_time: '',
      $page_referrer: ''
    }
  }
  /**
   * 初始化
   */
  init(routerModel?: routerOption) {
    this.routerModel = routerModel
    this.initEvent()
  }
  /**
   * 重写pushState/replaceState事件
   */
  initEvent() {
    window.history['pushState'] = this.createHistoryEvent('pushState')
    window.history['replaceState'] = this.createHistoryEvent('replaceState')
    if (this.routerModel == 'history') {
      this.captureEvents(['pushState', 'replaceState', 'popstate'])
    }
    if (this.routerModel == 'hash') {
      this.captureEvents(['hashchange'])
    }
  }
  /**
   * 绑定hashchange、popstate事件
   */
  captureEvents<T>(MouseEventList: string[]) {
    MouseEventList.forEach(event => {
      this.addEvent(window, event, (e: MouseEvent) => {
        this.trigger()
      })
    })
  }
  /**
   * 创建事件
   * params history事件名
   */
  createHistoryEvent = <T extends keyof History>(type: T): (() => any) => {
    const origin = history[type]
    const self = this
    return function (this: any) {
      const res = origin.apply(this, arguments)
      self.trigger()
      return res
    }
  }
  /**
   * 修改页面信息、并合并自定义属性
   * @param  customProps 自定义属性
   */
  getPresetProperties(customProps: any) {
    const current_url = location.href
    this.baseParams.$page_referrer = this.baseParams.$page_url
    this.baseParams.$page_url = current_url
    const current_time = utils.dateFormat(new Date())
    this.baseParams.$leave_time = current_time
    this.baseParams.$enter_time = this.last_time
    this.last_time = current_time
    let _customProps = typeof customProps === 'object' && customProps !== null ? customProps : {}
    return Object.assign(this.baseParams, _customProps)
  }
  /**
   * 绑定浏览事件
   */
  trigger(prop?: any) {
    const para = this.getPresetProperties(prop)
    collect.getViewEvent(para)
  }
}
export default new ViewEvent()