Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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”


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...