Angular 2+ window.onfocus and windows.onblur

Therefore, I need to control in Angular 2 or 4 when the browser tab of my application is focused or not. Is it possible to use window.onfocus and window.onblur ?

thanks a lot

+12
source share
2 answers

You can use the component with @HostListener .

Sort of:

 @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 make sure you don't have multiple WindowComponent running at the same time, because you will have unexpected behavior, as each instance will respond to these events.

+19
source

Turns out this doesn't work in services , which was my requirement. My decision did 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 if I did this in the “right” way, but it works on Chrome. What I'm not sure of is whether I should destroy the event listener or not, and whether it works in other browsers. Let me know if I accidentally shoot myself in the foot here. Updates the answer, if so, or removes it, if necessary.

0
source

Source: https://habr.com/ru/post/1270500/


All Articles