如何衡量在页面上花费的时间?

Ric*_*nop 54 javascript jquery

我想测量用户在页面上花费的时间(以浮点数表示的整数或分钟数).我知道有一个卸载事件,我可以在他们离开页面时触发.但是如何获得他们已经在那里度过的时间?

jas*_*man 52

接受的答案是好的,但(作为替代方案)我已经将一些工作放入一个小的JavaScript库中,该库计算用户在网页上的时间.它具有更准确(但并不完美)跟踪用户实际与页面交互的时间的额外好处.它会忽略用户切换到不同标签,闲置,最小化浏览器等的时间.在接受的答案中建议的Google Analytics方法有缺点(据我所知),它只会检查您的新请求何时处理域.它将先前的请求时间与新请求时间进行比较,并调用"在您的网页上花费的时间".它实际上并不知道是否有人正在查看您的页面,最小化浏览器,将标签切换到自上次加载页面以来的3个不同的网页等.

编辑:我已更新示例以包含当前的API使用情况.

编辑2:更新托管项目的域

https://github.com/jasonzissman/TimeMe.js/

其用法示例:

包含在您的页面中:

<!-- Download library from https://github.com/jasonzissman/TimeMe.js/ -->
<script src="timeme.js"></script>
<script type="text/javascript">
TimeMe.initialize({
    currentPageName: "home-page", // page name
    idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>
Run Code Online (Sandbox Code Playgroud)

如果您想自己向后端报告时间:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
Run Code Online (Sandbox Code Playgroud)

TimeMe.js还支持通过websockets发送计时数据,因此您不必尝试强制完整的http请求进入document.onbeforeunload事件.

  • 伟大的思想。TimeMe 实际上就是这样做的——如果您在可配置的时间内处于“空闲”状态(没有鼠标移动、按键等),那么它会停止跟踪您的时间。我实际上在上个月左右更新了 TimeMe.js,以重新设计很多内部逻辑。暗示在聚焦新窗口时计时器仍然运行的原始评论似乎不再是问题。 (2认同)
  • TimeMe不会捕获在iframe(也没有运行TimeMe)中花费的时间。 (2认同)

Kev*_*lan 35

如果您使用Google Analytics,他们会提供此统计信息,但我不确定他们是如何获得的.

如果您想自己动手,则需要将一些AJAX请求发送到您的服务器进行记录.

jQuery有一个.unload(...)方法,您可以使用如下:

$(document).ready(function() {
  var start = new Date();

  $(window).unload(function() {
      var end = new Date();
      $.ajax({ 
        url: "log.php",
        data: {'timeSpent': end - start},
        async: false
      })
   });
});
Run Code Online (Sandbox Code Playgroud)

在此处查看更多信息:http://api.jquery.com/unload/

这里唯一需要注意的是它使用了javascript的beforeunload事件,它并不总是有足够的时间来发出像这样的AJAX请求,所以合理地说你会丢失很多数据.

另一种方法是使用某种类型的"STILL HERE"消息定期轮询服务器,该消息可以更一致地处理,但显然更昂贵.

  • 当用户第一次加载JS时发送请求可能是一个更好的主意,而当他离开页面时则发送另一个请求.这样你就无法做出任何破解. (3认同)

Dav*_*und 9

我想说最好的办法是跟踪服务器上每个会话ID的请求时间.用户在最后一页上花费的时间是当前请求的时间与先前请求的时间之间的差异.

这不会捕获用户访问的最后一页(即,当没有其他请求时),但我仍然采用这种方法,因为否则我必须提交请求onunload,这将非常容易出错.


Jac*_*fin 8

.()

Running inline code to get the time that the user got to the page blocks the loading of the page. Instead, use performance.now() which shows how many milliseconds have elapsed since the user first navigated to the page. Date.now, however, measures clock-time which can differ from navigation-time by a second or more due to factors such as Time resynchonization and leap seconds. performance.now() is supported in IE10+ and all evergreen browsers (evergreen=made for fun, not for profit). The earliest version of internet explorer still around today is Internet Explorer 11 (the last version) since Microsoft discontinued Windows XP in 2014.

(function(){"use strict";

var secondsSpentElement = document.getElementById("seconds-spent");
var millisecondsSpentElement = document.getElementById("milliseconds-spent");

requestAnimationFrame(function updateTimeSpent(){
    var timeNow = performance.now();
    
    secondsSpentElement.value = round(timeNow/1000);
    millisecondsSpentElement.value = round(timeNow);
    
    requestAnimationFrame(updateTimeSpent);
});
var performance = window.performance, round = Math.round;
})();
Run Code Online (Sandbox Code Playgroud)
Seconds spent on page:&nbsp; <input id="seconds-spent" size="6" readonly="" /><br />
Milliseconds spent here: <input id="milliseconds-spent" size="6" readonly="" />
Run Code Online (Sandbox Code Playgroud)


hex*_*mal 6

我认为最好的方法是将时间存储在cookie中的onload和unload事件处理程序中,然后在服务器端脚本中进行分析

  • 这仅在用户转到服务器上的另一个页面时才有效. (4认同)

mar*_*pie 6

除了Jason的回答之外,如果你不想使用库,这里有一小段代码可以解决问题,它考虑用户切换标签或聚焦另一个窗口.

let startDate = new Date();
let elapsedTime = 0;

const focus = function() {
    startDate = new Date();
};

const blur = function() {
    const endDate = new Date();
    const spentTime = endDate.getTime() - startDate.getTime();
    elapsedTime += spentTime;
};

const beforeunload = function() {
    const endDate = new Date();
    const spentTime = endDate.getTime() - startDate.getTime();
    elapsedTime += spentTime;

    // elapsedTime contains the time spent on page in milliseconds
};

window.addEventListener('focus', focus);
window.addEventListener('blur', blur);
window.addEventListener('beforeunload', beforeunload);
Run Code Online (Sandbox Code Playgroud)