JS手机应用前台后台切换监听

694 阅读1分钟
export class AppBackstageReception {
    // eslint-disable-next-line no-useless-constructor
    constructor() {
        this.callback = null;
        this.state = null;
        this.eventOptions = {
            pauseEven: null,
            resumeEven: null,
            visEven: null
        };
    }
    init(callback) {
        if (typeof callback !== 'function') throw new TypeError('回调函数是必须的');
        this.clear();
        this.callback = callback;
        this.eventOptions.visEven = () => {
            if (document.visibilityState === 'visible') { // 页面可见
                // 防止手机二次触发回调
                if (this.state !== null && this.state === 1) return;
                this.state = 1;
                this.callback && this.callback(true, {eventMessage: '从前台切换到后台', state: 1});
            } else if (document.visibilityState === 'hidden') { // 页面隐藏
                 // 防止手机二次触发回调
              	if (this.state !== null && this.state === 0) return;
                this.state = 0;
                this.callback && this.callback(false, {eventMessage: '从前台切换到后台', state: 0});
            }
        };
        document.addEventListener('visibilitychange', this.eventOptions.visEven);
    }
    clear() {
        if (this.callback === null) return;
        this.callback = null;
        document.removeEventListener('visibilitychange', this.eventOptions.resumeEven);
    }
}