javascript 如何检查浏览器是否获得焦点

javascript how check if browser got focus

我有一个基于 Meanjs 的工作聊天,我想向它添加一个我在其他可用聊天中看到的新功能:

特点: 1. 当收到消息时,window 的标题开始在原来的内容和通知消息之间切换,例如"new message" 2.当浏览器或标签获得焦点时,停止正在进行的activity并重置回静态页面标题

第一个就是简单的有一个定时器,在一段时间内改变页面标题,但我不知道如何获得浏览器获得或失去焦点的事件。

我可以简单地询问 "how detect focus" 浏览器,但我解释了我的目的是希望了解这个特定 use-case 的最佳实践并了解更多信息。

欢迎并欣赏课程。

简单地说,您可以使用本机 javascript 事件处理程序检查 window 是否处于焦点上。我们将使用 window.onblur 检查 window 是否未聚焦,并使用 window.onfocus 检查 window 是否聚焦。

    window.onblur = function(){
      // do some event handler here...in your case, to show new message alert on the title if the user receive new message.
       newMessageChecker();
    }
    window.onfocus = function(){
       // invoke another function to bring back your default title and destroy the Interval you have created.
       destroyMessageChecker();
    }
    function newMessageChecker(){
      // check if the user have new message. you may use setInterval method
      window.messageChecker = setInterval(function(){
            // if true, do some stuff like this
               document.title = "New Message("+ messageCount +") : " + yourDefaultTitleValue;
      }, 3000);
    }
    function destroyMessageChecker(){
      // change your title to default value
      document.title = yourDefaultTitleValue;
      clearInterval(window.messageChecker);
    }

有关 window 活动的更多信息,请查看此 link Window Event Attributes. if you prefer to use jQuery please check this page Using jQuery to bind “focus” and “blur” functions for “window”