Execute code only if the user is not in the tab

Asked

Viewed 109 times

1

I wonder how I can make to run a script (in this case are those desktop notifications) only if the user is not open tab, I mean, I want to send a desktop notification to it only if it’s not open (I’m doing it with ajax) but I don’t know how to do it in javascript! I tried to use:

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

but it didn’t 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);
                        }
                });

            });

3 answers

1

In fact the $.focus has for purpose to detect when the user is and not when it left, you must utilize the features $.focusout or $.blur:

$(window)
.focusout(function() {

})
.blur(function() {

});
  • 1

    I used . focusout but it did not work, now it does not send the notification, I will edit the question and put the full code!

  • 1

    It’s just that I don’t really care when he left, I just need to check whether the tab is open or not

  • 1

    tried with the Blur?

  • I tried and I didn’t either, but I managed to solve!

0

From what I understand and using what has already been suggested by the other answers: save the status page on a flag, updating it as the user focuses or hides the tab.

const pagina = { sendoVista: true };
$(window).focus(function() {
    pagina.sendoVista = true;
}).blur(function() {
    pagina.sendoVista = false;
});

In AJAX code (or other type) that displays notifications, just ask the flag and trigger the alerts only when the user is in another tab.

Of course everything down here is subject to change.

0

I was able to solve it this way:

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

if(mouseFora) {

// CODIGO

}

Browser other questions tagged

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