最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to know how long a user has spent on a page? - Stack Overflow

programmeradmin3浏览0评论

Say I've a browser extension which runs JS pages the user visits.

Is there an "outLoad" event or something of the like to start counting and see how long the user has spent on a page?

Say I've a browser extension which runs JS pages the user visits.

Is there an "outLoad" event or something of the like to start counting and see how long the user has spent on a page?

Share Improve this question asked Jul 23, 2013 at 7:35 dsp_099dsp_099 6,12120 gold badges78 silver badges131 bronze badges 2
  • there is a way,you dont need a js for that..you can initiate a timer on pageload and keep on inserting values in your database.i will just give you a demo..wait 10 min – HIRA THAKUR Commented Jul 23, 2013 at 7:37
  • 2 The best approach wouldn't be counting or running a timer, but to check the time onLoad and onBeforeUnload and calculate the difference. – Vala Commented Jul 23, 2013 at 7:42
Add a comment  | 

7 Answers 7

Reset to default 5

I am assuming that your user opens a tab, browses some webpage, then goes to another webpage, comes back to the first tab etc. You want to calculate exact time spent by the user. Also note that a user might open a webpage and keep it running but just go away. Come back an hour later and then once again access the page. You would not want to count the time that he is away from computer as time spent on the webpage. For this, following code does a docus check every 5 minutes. Thus, your actual time might be off by 5 minutes granularity but you can adjust the interval to check focus as per your needs. Also note that a user might just stare at a video for more than 5 minutes in which case the following code will not count that. You would have to run intelligent code that checks if there is a flash running or something.

Here is what I do in the content script (using 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);
    }
}

onbeforeunload should fit your request. It fires right before page resources are being unloaded (page closed).

<script type="text/javascript">

function send_data(){
            $.ajax({
                url:'something.php',
                type:'POST',
                data:{data to send},
                success:function(data){
                //get your time in response here
                }
            });
        }
//insert this data in your data base and notice your timestamp


 window.onload=function(){ send_data(); }
 window.onbeforeunload=function(){ send_data(); }

</script>

Now calculate the difference in your time.you will get the time spent by user on a page.

For those interested, I've put some work into a small JavaScript library that times how long a user interacts with a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc.

Edit: I have updated the example to include the current API usage.

http://timemejs.com

An example of its usage:

Include in your page:

<script src="http://timemejs.com/timeme.min.js"></script>
<script type="text/javascript">
TimeMe.initialize({
    currentPageName: "home-page", // page name
    idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>

If you want to report the times yourself to your backend:

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);

TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full http request into the document.onbeforeunload event.

The start_time is when the user first request the page and you get the end_time by firing an ajax notification to the server just before the user quits the page :

window.onbeforeunload = function () {
  // Ajax request to record the page leaving event.
  $.ajax({ 
         url: "im_leaving.aspx", cache: false
  });
};

also you have to keep the user session alive for users who stays long time on the same page (keep_alive.aspxcan be an empty page) :

var iconn = self.setInterval(
  function () { 
    $.ajax({ 
         url: "keep_alive.aspx", cache: false }); 
    }
    ,300000
);

then, you can additionally get the time spent on the site, by checking (each time the user leaves a page) if he's navigating to an external page/domain.

Revisiting this question, I know this wouldn't be much help in a Chrome Ext env, but you could just open a websock that does nothing but ping every 1 second and then when the user quits, you know to a precision of 1 second how long they've spent on the site as the connection will die which you can escape however you want.

Try out active-timeout.js. It uses the Visibility API to check when the user has switched to another tab or has minimized the browser window.

With it, you can set up a counter that runs until a predicate function returns a falsy value:

ActiveTimeout.count(function (time) {
    // `time` holds the active time passed up to this point.
    return true; // runs indefinitely
});
发布评论

评论列表(0)

  1. 暂无评论