Node.JS&Socket.io – 检查选项卡是否被选中

对于我的聊天,我想要通知。 这些通知就像Gitter的通知一样,它会改变html标题以显示你的消息。 我GOOGLE了如何做到这一点,但所有的答案只有通过检查选项卡更改时工作。 例如,

socket.on('chat message', function (msg) { // Append the message appendMessage(msg); // Check if the window is focused if (window.onfocus) { // If it is, there's no need to show there's a new message document.title = "ChatProject"; }else{ // If the user is on another tab, show there's a new message document.title = "[!] ChatProject"; } }); 

使用上面的代码,它总是显示通知你是否在选项卡上。 我如何才能让它只在有新消息时显示?

window.onfocus是一个事件。 不是一个国家。

通过给事件添加一个getter和setter,你可以得到所描述的行为。

 /////////////////////// //Setting OnFocusSate// /////////////////////// var isFocused = true; function onFocus(){ isFocused = true; }; function onBlur() { isFocused = false; }; window.onfocus = onFocus; window.onblur = onBlur; /////////////////////// //Example Event Check// /////////////////////// socket.on('chat message', function (msg) { // Append the message appendMessage(msg); // Check if the window is focused if (isFocused) { // If it is, there's no need to show there's a new message document.title = "ChatProject"; }else{ // If the user is on another tab, show there's a new message document.title = "[!] ChatProject"; } }); 

神秘:这个工作,但是当你点击标签时,通知不会消失。 所以,我们必须改变if语句

  if (!isFocused) { // If the user is on another tab, show there's a new message document.title = "[!] ChatProject"; } 

然后将其添加到它下面

 window.onfocus = function() { document.title = "ChatProject"; }