用于页面访问,心跳监测的方法

1 页面首次进入是否触发心跳

2 网页tab切换时,切回来是否触发心跳以及针对切回tab触发心跳的标识字段

3 浏览标识和心跳标识,用于区分首次进入以及后续浏览时触发的心跳上报

4 心跳上报间隔

/**
 * @param {string} page  必传,页面标识 
 * @param {object} options 可选,一些配置项 见 defaultOptions
 */
export default class HeartDance{
  constructor(page, options = {}){
    if(!page){
       throw new SyntaxError("page is required!")
    }
    const defaultOptions  = {
      reportBrowse: true, // 是否上报浏览
      reportTabBack: true, // 切回tab 是否立刻上报心跳
      tabBackInfo:{key:'itemValue',value:'tag'}, // 切回tab 上报心跳标识
      browse: 'browse', // 浏览标识
      beat:'beat', // 心跳标识
      heartDanceTime:30000, // 心跳间隔
    };
    this.danceInfo = {};
    this.page = page; // 当前页面标识
    this.options =  Object.keys(options).length === 0 ? 
                    defaultOptions : this.#mergeOptions(defaultOptions, options);
  }
  /**
   * 产生心跳监听
   * @param {*} fn 定时回调函数
   */
  generateHeartDance(fn){
    if(!fn || typeof fn !== 'function'){
      throw new TypeError(`${fn} is not  a function`);
    }
    const { reportBrowse, browse, beat, heartDanceTime, tabBackInfo} = this.options;
		const page = this.page;
    // 首次进入页面,上报浏览
    if(reportBrowse){
      fn(page, browse);
    }
    // 定时心跳
    if(!document.hidden){
      this.danceInfo.t = setInterval(() => {
        fn(page, beat);
      }, heartDanceTime)
    }
  
    this.danceInfo.listener = () => {
      if(!document.hidden){
        // tab切换回来显示 立刻发一次心跳
        fn(page, beat,{[tabBackInfo.key]: tabBackInfo.value});
        // 新的定时心跳
        this.danceInfo.t = setInterval(() => {
          fn(page, beat);
        }, heartDanceTime)
      }else{
        // tab隐藏 清计时器
        clearInterval(this.danceInfo.t);
      }
    }
    document.addEventListener('visibilitychange', this.danceInfo.listener);
  }
  /**
   * 清除定时器 去掉监听事件
   */
  removeHeartDance(){
    clearInterval(this.danceInfo.t);
    document.removeEventListener('visibilitychange', this.danceInfo.listener);
  }
  /**
   * 合并可选项参数
   * @param {*} source 
   * @param {*} options 
   * @returns 
   */
  #mergeOptions(source, options) {
    for(const key in options){
      if(isObject(options[key])){
        source[key] = this.#mergeOptions(source[key], options[key]);
      }else{
        source[key] = options[key];
      }
    }  

    function isObject(val){
      return val !== null && typeof val === 'object'
    }
    return source;
  }
  
}

基本使用:

 const heartDance = new HeartDance('pageName', { heartDanceTime: 10000 });
 heartDance.generateHeartDance(fn); // fn 是回调,可以是接口,也可以是其它用于记录的方法
 heartDance.removeHeartDance() // 在合适的时机清除监听,比如页面离开或者卸载

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值