我需要在 Angular 2 或 4 中管理应用程序的浏览器选项卡是否聚焦。有没有办法使用 window.onfocus
和 window.onblur
?
非常感谢。
我需要在 Angular 2 或 4 中管理应用程序的浏览器选项卡是否聚焦。有没有办法使用 window.onfocus
和 window.onblur
?
非常感谢。
@HostListener
的组件。
类似这样:@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
}
}
请确保您没有同时运行多个WindowComponent
,因为这将导致意外行为,因为每个实例都会对这些事件做出反应。
@Injectable()
export class WindowService {
constructor(){
window.addEventListener('focus', event => {
console.log(event);
});
window.addEventListener('blur', event => {
console.log(event);
});
}
}
我不确定我是否以“正确”的方式完成了它,但它在Chrome上运行。我不确定的是是否应该销毁事件监听器,以及它在其他浏览器中是否有效。如果我无意中自毁长城,请告诉我。如果有必要,我将更新答案或删除它。
export const WINDOW_FOCUS = new InjectionToken<Observable<boolean>>(
'Shared Observable based on `window focus/blurred events`',
{
factory: () => {
return merge(fromEvent(window, 'focus'), fromEvent(window, 'blur')).pipe(
startWith(null),
map(() => window.document.hasFocus()),
distinctUntilChanged(),
share(),
);
},
},
);
@Injectable()
export class SomeService {
constructor(
@Inject(WINDOW_FOCUS) private readonly windowFocus$: Observable<boolean>
) {}
}
onFocus
函数将在浏览器触发window.onfocus
时被触发,blur
同理。 - dlcardozo