Execute code only if the user is not on the tab

1

I would like to know how I can do to run a script (in this case it is those desktop notifications) only if the user does not have the open tab , ie I want to send a desktop notification to it only if it does not have the site open (I'm doing this with ajax) but I do not know how to do this in javascript! I tried using:

$(window).focus(function(){
  //your code
});

But it did not work ...

Thank you!

Complete code:

$(window).focusout(function() {

            Notification.requestPermission(function (permission) {
                        // Whatever the user answers, we make sure we store the information
                        if (!('permission' in Notification)) {
                            Notification.permission = permission;
                        }

                        // If the user is okay, let's create a notification
                        if (permission === "granted") {
                            var options = {
                                body: "TEXTO_DA_NOTIFICACAO",
                                icon: "IMAGEM",
                                dir : "ltr"
                            };
                            var notification = new Notification("TITULO",options);
                        }
                });

            });
    
asked by anonymous 18.02.2016 / 18:38

2 answers

1

In fact, $.focus is intended to detect when the user is and not when he left, you should use $.focusout or $.blur :

$(window)
.focusout(function() {

})
.blur(function() {

});
    
18.02.2016 / 18:46
0

I was able to resolve it as follows:

var mouseFora = !$("html").is(":hover");

if(mouseFora) {

// CODIGO

}
    
18.02.2016 / 20:46