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

Asked

Viewed 301 times

2

Explaining the problem

I’m working with sockets, and would like to know how to put a notification only when the tab is out of focus.

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

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

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

In short

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

Can be Javascript or Jquery.

2 answers

0


An extremely simple solution with jquery. I can’t believe I didn’t think of it before.

var notification;

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

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

That way when the window gets focused, it will ACTIVATE notifications, and when you lose focus, you will DEACTIVATE notifications. This without needing many lines of code, or any kind of listening.

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

socket.on('newMessage', function(message) {
    if (notification) {
        notifyMe(message.text);
    }
});

0

Add and remove the Systener for the event according to the Blur and Focus from the field.

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

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

window.addEventListener('focus', receberNotificacoes);
window.addEventListener('blur', removeListener('notificacoes'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.