Service to check if application browser tab is active or not

This service is useful for those scenarios when you don’t want to run a background task when the user has another tab active. Or to trigger some code when the user returns to the application tab.

Many applications have background tasks running, such as refreshing data or checking for object statuses. However, these tasks are often unnecessary when the user is using another browser tab.
You can use @HostListener to detect the tab status in an Angular component, but not in a service.
An alternative is therefore to use fromEvent.

import { Injectable } from '@angular/core';
import { BehaviorSubject, fromEvent } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class BrowserService {
  private tabStatus = new BehaviorSubject<boolean>(true);
  public tabStatus$ = this.tabStatus.asObservable();

  public isTabActive(): boolean {
    return this.tabStatus.getValue();
  }

  constructor() {
    const visibilityChange$ = fromEvent(document, 'visibilitychange');
    visibilityChange$.subscribe(() => {
      if (document.visibilityState === 'visible') {
        this.tabStatus.next(true);
      } else {
        this.tabStatus.next(false);
      }
    });
  }
}

I also added an isTabActive() method for convenience for client code that doesn’t need to subscribe for changes and just needs to check the tab status in some logic.

Trackback URL: https://codeblog.silfversparre.com/2023/06/service-to-check-if-application-browser-tab-is-active-or-not/trackback/