3

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.

Akanksha Gaur
  • 2,636
  • 3
  • 26
  • 50

3 Answers3

5

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.

kklimczak
  • 623
  • 4
  • 10
3

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>
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
2

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);
    }
}
Pare Tr
  • 21
  • 2