本文最后更新于:2024年9月3日 早上
在某些应用场景可能会遇到需要计算用户在某页面的停留时间的类似需求,特总结如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>js计算页面停留时间_www.jbxue.com</title> <script type="text/javascript" src="jquery.js"></script> </head> <body onload="init(); window.setTimeout('show_secs()',1);" onbeforeunload="return myFunction()"> <script language="javascript">
var ap_name = navigator.appName; var ap_vinfo = navigator.appVersion; var ap_ver = parseFloat(ap_vinfo.substring(0,ap_vinfo.indexOf('('))); var time_start = new Date(); var clock_start = time_start.getTime(); var dl_ok=false; function init (){ if(ap_name=="netscape" && ap_ver>=3.0) dl_ok=true; return true; } function get_time_spent (){ var time_now = new Date(); return((time_now.getTime() - clock_start)/1000); } function show_secs (){ var i_total_secs = Math.round(get_time_spent()); var i_secs_spent = i_total_secs % 60; var i_mins_spent = Math.round((i_total_secs-30)/60); var s_secs_spent = "" + ((i_secs_spent>9) ? i_secs_spent : "0" + i_secs_spent); var s_mins_spent ="" + ((i_mins_spent>9) ? i_mins_spent : "0" + i_mins_spent); document.fm0.time_spent.value = s_mins_spent + ":" + s_secs_spent; window.setTimeout('show_secs()',1000); }
window.onbeforeunload = function(event){ s1(2000); var arr = [0, 1, 2, 3]; localStorage.setItem("num", arr); console.log(localStorage.getItem("num")); console.log("您在网站"+ document.URL+"停留时间(分:秒):"+document.fm0.time_spent.value); if(window.is_confirm !== false){ window.event.returnValue="2.确定要退出本页吗?"; } };
function myFunction(){ s1(2000);
console.log("您在网站"+ document.URL+"停留时间(分:秒):"+document.fm0.time_spent.value);
window.event.returnValue="3.确定要退出本页吗?";
};
function sleep(numberMillis) { var now = new Date(); var exitTime = now.getTime() + numberMillis; while (true) { now = new Date(); if (now.getTime() > exitTime) return; } } function s(){ sleep(2000); alert("您在网站"+ document.URL+"停留时间(分:秒):"+document.fm0.time_spent.value); }
function s1(sec){ setTimeout(function(){ alert("您在网站"+ document.URL+"停留时间(分:秒):"+document.fm0.time_spent.value); },sec); } </script> <form name="fm0" onsubmit="0"> <font color="#888888" size="-1">您在本网页的停留时间:</font> <input type="text" name="time_spent" size=7 onfocus="this.blur()"> <input type="button" value="暂停2秒" onclick="s1(2000)" /> <a href="http://blog.csdn.net/davislien/article/details/47685831">参考链接</a> </form> </body>
|