当前位置:   article > 正文

用于页面访问,心跳监测的方法_心率数据在网页上如何展示出来

心率数据在网页上如何展示出来

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

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

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

4 心跳上报间隔

  1. /**
  2. * @param {string} page 必传,页面标识
  3. * @param {object} options 可选,一些配置项 见 defaultOptions
  4. */
  5. export default class HeartDance{
  6. constructor(page, options = {}){
  7. if(!page){
  8. throw new SyntaxError("page is required!")
  9. }
  10. const defaultOptions = {
  11. reportBrowse: true, // 是否上报浏览
  12. reportTabBack: true, // 切回tab 是否立刻上报心跳
  13. tabBackInfo:{key:'itemValue',value:'tag'}, // 切回tab 上报心跳标识
  14. browse: 'browse', // 浏览标识
  15. beat:'beat', // 心跳标识
  16. heartDanceTime:30000, // 心跳间隔
  17. };
  18. this.danceInfo = {};
  19. this.page = page; // 当前页面标识
  20. this.options = Object.keys(options).length === 0 ?
  21. defaultOptions : this.#mergeOptions(defaultOptions, options);
  22. }
  23. /**
  24. * 产生心跳监听
  25. * @param {*} fn 定时回调函数
  26. */
  27. generateHeartDance(fn){
  28. if(!fn || typeof fn !== 'function'){
  29. throw new TypeError(`${fn} is not a function`);
  30. }
  31. const { reportBrowse, browse, beat, heartDanceTime, tabBackInfo} = this.options;
  32. const page = this.page;
  33. // 首次进入页面,上报浏览
  34. if(reportBrowse){
  35. fn(page, browse);
  36. }
  37. // 定时心跳
  38. if(!document.hidden){
  39. this.danceInfo.t = setInterval(() => {
  40. fn(page, beat);
  41. }, heartDanceTime)
  42. }
  43. this.danceInfo.listener = () => {
  44. if(!document.hidden){
  45. // tab切换回来显示 立刻发一次心跳
  46. fn(page, beat,{[tabBackInfo.key]: tabBackInfo.value});
  47. // 新的定时心跳
  48. this.danceInfo.t = setInterval(() => {
  49. fn(page, beat);
  50. }, heartDanceTime)
  51. }else{
  52. // tab隐藏 清计时器
  53. clearInterval(this.danceInfo.t);
  54. }
  55. }
  56. document.addEventListener('visibilitychange', this.danceInfo.listener);
  57. }
  58. /**
  59. * 清除定时器 去掉监听事件
  60. */
  61. removeHeartDance(){
  62. clearInterval(this.danceInfo.t);
  63. document.removeEventListener('visibilitychange', this.danceInfo.listener);
  64. }
  65. /**
  66. * 合并可选项参数
  67. * @param {*} source
  68. * @param {*} options
  69. * @returns
  70. */
  71. #mergeOptions(source, options) {
  72. for(const key in options){
  73. if(isObject(options[key])){
  74. source[key] = this.#mergeOptions(source[key], options[key]);
  75. }else{
  76. source[key] = options[key];
  77. }
  78. }
  79. function isObject(val){
  80. return val !== null && typeof val === 'object'
  81. }
  82. return source;
  83. }
  84. }

基本使用:

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/242081
推荐阅读
相关标签
  

闽ICP备14008679号