javascript how check if browser got focus

亡梦爱人 提交于 2021-02-05 08:01:49

问题


I have a working chat based on Meanjs and I would like to add a new feature to it that I see on other chats available:

Feature: 1. when a message is received, the title of the window starts to switch between what it was, and a notification message like "new message" 2. when the browser or tab receives the focus, to stop the ongoing activity and reset back to the static page title

The first one is simply to have a timer and change the page title during an interval, but I don't know how to get the event of the browser getting or losing the focus.

I could simply ask "how detect focus" for the browser, but I explained my purpose to hopefully know the best practice in this particular use-case and learn more.

Will welcome and appreciate lessons.


回答1:


Simply, you can check whether window is on focus or not by using native javascript event handler. we will use window.onblur to check if window isn't on focus and use window.onfocus to check if window is on focus.

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

for more information about window event, please take a look at this link Window Event Attributes. if you prefer to use jQuery please check this page Using jQuery to bind “focus” and “blur” functions for “window”



来源:https://stackoverflow.com/questions/30008631/javascript-how-check-if-browser-got-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!