如何解决Javascript:网页上的条件计数时间和广播自定义事件
我有以下自定义用例需要在纯 JavaScript 客户端中解决
计算用户在当前用户会话中在网站的特定页面组上花费的总时间。如果花费的时间达到特定时间限制,广播事件通知。
这里的计算是基于 maxTime 限制和匹配某组页面的 URL 路径。
www.abc.com 是站点,如果用户访问了
下的所有页面
abc.com/B/
或
abc.com/x/a.html
或
abc.com/y/b.html,计算时间
时间是15秒广播给所有人并重置。
使用可以访问差异。同一会话中的页面,其中某些页面的时间需要不断添加,而某些页面不计算在内,一旦用户返回特定页面,继续计时。
因此,尝试了解如何捕获页面 URL 条件并在逻辑中用于计算特定页面组和站点上的时间是 SPA(软导航)页面和经典页面以及何时开始和暂停计数的混合。
var startTiming=new TimeMeasure([‘www.abc.com/b/*’,”www.ac.com/x/a.html”],15)
这里是我的班级设计的高水平解释我想要做什么
var TimeMeasure = (function() {
function TimeMeasure(path,maxTimeMS) {
this.start = 0; //can be private
this.end = 0; //can be private
this.duration = 0; //can be private
this.pagePath = path||['*']; //array of string which contains diff regx or url pattern?
this.maxTime = maxTimeMS;
}
TimeMeasure.prototype = (function() {
function startFn() {
//Todo: check if current URL match with location path
this.start = new Date();
}
function updatetimeCalc() {
//TBD how check if current URL match with location path
this.end =new Date();
this.duration += (this.end.getTime() - this.start.getTime());
//save in cookie or storage
window.sessionStorage.setItem("timeongropofpage");
//can this.start=this.end ??
this.notifyIfMaxtimespent();
}
function awayFn() {
updatetimeCalc.call(this);
}
function unloadPage() {
updatetimeCalc.call(this);
}
return {
"init": function() {
this.start = 0;//or new Date()
this.end = 0;
this.duration = window.sessionStorage.getItem("timeongropofpage") || 0;
window.addEventListener('focus',startFn.bind(this));
window.addEventListener('blur',awayFn.bind(this));
window.addEventListener('beforeunload',unloadPage.bind(this));
//should click event also to consider to keep
//document.body.addEventListener('click',updatetimeCalc.bind(this));
//does blur and unload both call when page is unloading?
// on mobile browser befreunload call?
setTimeout(function(){ updatetimeCalc.call(this) }.bind(this),this.maxTime);
},"reset": function() {
this.start = 0;
this.end = 0;
this.duration = 0;
//reset storage or cookie
},"notifyIfMaxtimespent": function() {
if (this.duration >= this.maxTime) {
var event = new CustomEvent("userSpentTime",{
detail: {
timeSpent: true
}
});
//broadcast to all
window.dispatchEvent(event);
//rest all
//this.reset()
}
}
};
})();
return TimeMeasure;
}());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。