How do I perform functions when the window is out of focus?

2

Explaining the problem

I'm working with sockets, and I'd like to know how to place a notification only when the tab is out of focus.

That is, when the user is viewing the tab, it will not receive notifications, but if it leaves the tab, it will receive new notifications

What I really need is a function similar to .blur() of Jquery, but this function needs to work as a listener , that is, it stays there always waiting for something to happen. The problem with .blur() is that it fires only when the window loses focus.

$(window).blur(function(){
    console.log("Isto será executado apenas quando eu clicar em outra tab")
}

Summarizing

I need a function that runs on tabs that are not in the user's focus as it receives new notifications in real time.

It can be Javascript or Jquery.

    
asked by anonymous 09.02.2017 / 02:21

2 answers

0

An extremely simple solution with jquery. I can not even believe I did not think of that before.

var notification;

$(window).focus(function(){
    notification = false;
});

$(window).blur(function(){
    notification = true;
});

This way when the window gets focus, it will ENABLE notifications, and when it loses focus, DISABLE notifications. This does not require many lines of code, or any kind of listening .

To receive notifications if the window is out of focus. I just added if .

socket.on('newMessage', function(message) {
    if (notification) {
        notifyMe(message.text);
    }
});
    
24.02.2017 / 16:00
0

Add and remove the listener for the event according to the blur and focus of the field.

function removeListener(nome) {
    socket.removeListener(nome);
}

function receberNotificacoes () {
    socket.on('notificacoes', function (dados) { ... });
}

window.addEventListener('focus', receberNotificacoes);
window.addEventListener('blur', removeListener('notificacoes'));
    
09.02.2017 / 02:55