简体   繁体   中英

Javascript counter on php page

I've got a java script counter on my php page. (I should probably add that I don't know java script). It display's the time the user is active on the page. My problem is if the user presses F5 or refreshes the page the counter starts from 0 again. How do I change this so that it remembers the time? Help will be greatly appreciated.

Javascript:

var pageVisisted = new Date(); 

setInterval(function() {
    var timeOnSite = new Date() - pageVisisted;

    var secondsTotal = timeOnSite / 1000;
    var hours = Math.floor(secondsTotal / 3600);
    var minutes = Math.floor(secondsTotal / 60) % 3600;
    var seconds = Math.floor(secondsTotal)  % 60;

    document.getElementById('counter').innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);

The php page

<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
</head>
<body>
<?php
echo "<span id='counter'></span>";
?>
</body>

You can use a cookie to do this. Since you say you don't know javascript, you might want to just review this page http://www.quirksmode.org/js/cookies.html where it tells you how to read and write cookies. Every time you evaluate the time on the site, just read/write to that cookie and it will still be there when the page reloads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM