Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 510
Akanksha Gaur Avatar asked Aug 27 '26 17:08

Akanksha Gaur


2 Answers

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);
    }
}
like image 58
Pare Tr Avatar answered Aug 30 '26 08:08

Pare Tr


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.

like image 24
kklimczak Avatar answered Aug 30 '26 08:08

kklimczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!