Node.JS& Socket.io - 检查选项卡是否已选中

时间:2015-07-30 01:36:38

标签: javascript node.js

对于我的聊天,我想收到通知。这些通知将像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";
    }
});

使用上面的代码,始终会显示您是否在选项卡上的通知。如何才能在有新消息的情况下显示它?

1 个答案:

答案 0 :(得分:1)

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

Cryptic:这是有效的,但当您单击选项卡时,通知不会消失。因此,我们必须将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";
}