解决方法
我假设您的用户打开一个标签,浏览一些网页,然后转到另一个网页,返回到第一个标签等.您想要计算用户花费的确切时间.另请注意,用户可能会打开网页并保持其正常运行但只是离开.一小时后回来,然后再次访问该页面.您不希望将他离开计算机的时间计算在网页上花费的时间.为此,下面的代码每5分钟进行一次docus检查.因此,您的实际时间可能会偏离5分钟的粒度,但您可以根据需要调整间隔以检查焦点.另请注意,用户可能只是盯着视频超过5分钟,在这种情况下,以下代码将不计算在内.您必须运行智能代码来检查是否有闪存运行或其他东西.
这是我在内容脚本中所做的(使用jQuery):
$(window).on('unload',window_unfocused); $(window).on("focus",window_focused); $(window).on("blur",window_unfocused); setInterval(focus_check,300 * 1000); var start_focus_time = undefined; var last_user_interaction = undefined; function focus_check() { if (start_focus_time != undefined) { var curr_time = new Date(); //Lets just put it for 4.5 minutes if((curr_time.getTime() - last_user_interaction.getTime()) > (270 * 1000)) { //No interaction in this tab for last 5 minutes. Probably idle. window_unfocused(); } } } function window_focused(eo) { last_user_interaction = new Date(); if (start_focus_time == undefined) { start_focus_time = new Date(); } } function window_unfocused(eo) { if (start_focus_time != undefined) { var stop_focus_time = new Date(); var total_focus_time = stop_focus_time.getTime() - start_focus_time.getTime(); start_focus_time = undefined; var message = {}; message.type = "time_spent"; message.domain = document.domain; message.time_spent = total_focus_time; chrome.extension.sendMessage("",message); } }