赞
踩
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() // 在合适的时机清除监听,比如页面离开或者卸载
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。