Angular 2+ window.onfocus and windows.onblur

You can use a component with @HostListener.

Something like:

@Component({})
export class WindowComponent {

constructor(){}

    @HostListener('window:focus', ['$event'])
    onFocus(event: any): void {
        // Do something
    }

    @HostListener('window:blur', ['$event'])
    onBlur(event: any): void {
        // Do something
    }

}

Just check that you don't have multiple WindowComponent running at the same time, because you will have an unexpected behavior, due that each instance will react to these events.


Turns out this doesn't work in services, which was my requirement. My solution was doing it "the old way":

@Injectable()
export class WindowService {
    constructor(){
        window.addEventListener('focus', event => {
            console.log(event);
        });
        window.addEventListener('blur', event => {
            console.log(event);
        });
    }
}

Not sure I did it the "correct" way, but it works on Chrome. What I'm not sure about is if I should destroy the event listener or not, and if it works in other browsers. Let me know if I'm inadvertently shooting myself in the foot here. Will update answer if so, or delete it if need be.