Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript how check if browser got focus

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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”


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...