Akanksha Gaur
Akanksha Gaur

Reputation: 2686

Angular 7 detect browser tab became active

In our application, we have to get the user context from our backend service. If user context changes, application needs to reload. Since user could change their context in a different tab. We ping our backend service every 5 sec to check if user context has changed.

Is there a way to detect whether user has deactivated or activated the current tab? It would save pinging the backend every 5 sec.

User could change context in different tab of the same application or another application.

Upvotes: 6

Views: 15797

Answers (3)

Pare Tr
Pare Tr

Reputation: 81

If you need Angular way and need to access component level properties then do this way:

@HostListener('document:visibilitychange', ['$event'])
appVisibility() {
   if (document.hidden) {
      //do whatever you want
      this.appHidden = true;
      console.log("Hidden: " + this.appHidden);
    } 
    else {
      //do whatever you want
      this.appHidden = false;
      console.log("SHOWN: " + this.appHidden);
    }
}

Upvotes: 8

Rohit Tagadiya
Rohit Tagadiya

Reputation: 3730

CASE 1

Just add this EventListener in your constructor.

document.addEventListener("visibilitychange", function() {
      if (document.hidden) {
        //do whatever you want
        console.log("Hidden");
      }
      else {
        //do whatever you want
        console.log("SHOWN");
      }
});

CASE 2

See here If you change tab $(window).blur(function () function will call and If you again come to this tab $(window).focus(function () function will call. Add this code in your constructor

$(window).focus(function () {
      //do something
       console.log("You are in this tab");
});

$(window).blur(function () {
      //do something
       console.log("You left this tab");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click here and click outside of this..</p>

Upvotes: 3

kklimczak
kklimczak

Reputation: 633

Use hasFocus() method from: here, which store context of tab focus.

The hasFocus() method of the Document interface returns a Boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.

If you want an async version with an event listener use Page Visibility API.

Upvotes: 6

Related Questions