开发者

Is there a way track the focus on tab with Javascript?

  • We need to track the EFFECTIVE ti开发者_运维问答me on site of our users
  • Most users, when they're done, leave the tab open and move to another tab
  • Time on site it's extremely inaccurate

Is there a Javascript Event to track the "loss of focus" of the current tab ?


This should work both on tab switch and on browser window losing focus:

function onBlur() {
    document.body.className = 'blurred';
};
function onFocus(){
    document.body.className = 'focused';
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}


I would do something with mousemove and scroll and count a visitor as active as long as either of those trigger within some interval. That will also cover them leaving the browser open and leaving the computer.


Which tab you are talking about? Is it your Nav/menu tab or Browser tab. I feel, you mean browser tab! I think it is not possible accurately. But what if you track few events like mousemove, focus etc and then fire an event that same some data (counter) on server. When user is on your page then he will do something something like move mouse, click somewhere etc. So difference in first page load and last event can tell the usage stat.


Though question was asked long ago, it might still be found by someone. In this case, use Page Visibility API:

https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

document.visibilityState - to get a current tab state.
document.onvisibilitychange - to add a callback for state change.


  <script>
    document.onvisibilitychange = () => {
      if (document.visibilityState === "hidden") {
        console.log("tab inactive");
      }
      if (document.visibilityState === "visible") {
        console.log("tab active");
      }
    };
  </script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜