如何在浏览器页面切换到我的网站选项卡时创建事件,如gmail中的聊天框状态更改

How to create an event while browser page gets switched to my website tab like chat box status changes in gmail

本文关键字:gmail 创建 事件 状态 聊天 浏览器 网站 我的 选项      更新时间:2024-03-17

在我的网页中,有在线状态,如可用、空闲、繁忙等。如果我们直到10分钟才加载页面,状态将变为可用或空闲。一旦我返回到我的网页选项卡浏览器,如何创建一个用于将空闲状态更改为可用的事件,除非刷新页面。

这可以使用body元素上的mouseover事件来完成。

document.getElementsByTagName('body')[0].addEventListener("mouseover", function(){
   // If idle then set status to available
});

编辑:

这里有个主意。Window.requestAnimationFrame()函数仅在选项卡/窗口处于活动状态时执行。因此,如果未调用该函数,则意味着用户没有查看选项卡或选项卡未处于活动状态。

查看此示例。运行脚本,然后切换选项卡几秒钟,然后切换回

var isTabOpen=true;
var tabTimer=null;
function tabCheck(){
  //This function is only called when the tab is open.
  
  if(tabTimer) clearTimeout(tabTimer);
  
    tabTimer = setTimeout(function(){
      isTabOpen = false;
    },1000);
  
  isTabOpen=true;
   
}
setInterval(function(){
  window.requestAnimationFrame(tabCheck);
  document.getElementsByTagName('body')[0].innerHTML += (isTabOpen+'<br/>');
},1000);