wuhu-torn-helper/src/ts/class/action/WindowActiveState.ts
2023-04-24 11:07:54 +08:00

31 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import uuidv4 from "../../func/utils/uuidv4";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
@ClassName('WindowActiveState')
@Injectable()
export default class WindowActiveState {
private isFocus = false;
private uuid = uuidv4();
constructor() {
if (self !== top) return null;
localStorage.setItem('whuuid', this.uuid);
document.addEventListener('visibilitychange',
() => (document.visibilityState !== 'hidden') && (localStorage.setItem('whuuid', this.uuid))
);
addEventListener('focus', () => this.isFocus = true);
addEventListener('blur', () => this.isFocus = false);
}
// 当前实例是否激活
get(): boolean {
// 当前窗口获得了焦点 优先级最高
if (this.isFocus) return true;
// 可视性
if (!document.hidden) return true;
// 全部在后台使用唯一id判断
return this.uuid === localStorage.getItem('whuuid')
}
}