js脚本计算页面停留时间实例

发布时间:2021-01-17编辑:脚本学堂
本文介绍了js计算页面停留时间的方法,一个js脚本计算页面停留时间的例子,有需要的朋友参考下。

1、加入html的<head></head>之间:
 

复制代码 代码示例:
<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 () // show the time user spent on the side
{
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);
}
// -->
</script>

2、加入html的<body></body>之间:
 

复制代码 代码示例:
<body onload="init(); window.settimeout('show_secs()',1);">
<form name="fm0" onsubmit="0">
<font size="-1"><i><font color="#888888">您在本网页的停留时间:</font></i></font><br>
<input type="text" name="time_spent" size=7 onfocus="this.blur()">
</form>
 

页面停留时间【方案2】[离开时弹出提示框][共1步]
1、加入heml的<body></body>之间:
 

复制代码 代码示例:
<script language="javascript">
<!-- begin
pageopen = new date();
function bye() {
pageclose = new date();
minutes = (pageclose.getminutes() - pageopen.getminutes());
seconds = (pageclose.getseconds() - pageopen.getseconds());
time = (seconds + (minutes * 60));
if (time == 1) {
time = (time + " second");
}
else {
time = (time + " seconds");
}
alert('您在本页停留了' + time + '.谢谢!!');
}
// end -->
</script>
<body onunload="bye()">3离开时弹出提示框
<script language="javascript" type="text/javascript">
window.onbeforeunload = function() { return("您真的要离开本页吗?"); }
</script>