Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

336
Views
Angular - reload page when tab is selected?

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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

window.addEventListener('focus', () => {
    window.location.reload();
});

Because it's Angular, I would drop that into my app.component.ts file under ngOnInit

Update

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);
    }
}
over 4 years ago · Santiago Trujillo Report

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!