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.
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With