Reputation: 93
Is there a way to trigger a function to reload the page when the user clicks the browser tab of my Angular app?
I believe this would be done with window.location.reload(), but I'm not sure how to make this line be triggered on tab selection.
I'm thinking this could be done by making the body/html have a "onfocus='reloadPage()'" attribute, but I don't want it to refresh 500 times as I'm moving my mouse around the page, just once when the tab is focused/clicked.
Upvotes: 3
Views: 6506
Reputation: 135
You could do that with javascript, paste this to your chrome console, and change tabs see how it works
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
}
function handleVisibilityChange() {
if (!document[hidden]) {
var initialPage = window.location.pathname;
window.location.replace(initialPage);
}
}
document.addEventListener(visibilityChange, handleVisibilityChange, false);
Upvotes: 1
Reputation: 4916
I like @enjoibp3 solution, but instead of adding event listeners and removing them. You're better off using @HostListener
(docs)
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
@HostListener('window:focus') onFocus() {
console.log('window focus');
window.location.reload();
}
}
See stackblitz code sample here and demo project here
Upvotes: 6
Reputation: 79
window.addEventListener('focus', () => {
window.location.reload();
});
Because it's Angular, I would drop that into my app.component.ts file under ngOnInit
Per the comments below you should also remove the event listener on destroy as well.
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
ngOnInit(): void {
window.addEventListener('focus', this.reloadPage);
}
reloadPage(): void {
window.location.reload();
}
ngOnDestroy(): void {
window.removeEventListener('focus', this.reloadPage);
}
}
Upvotes: 1