问题
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