h5做混合开发的时候,特殊的业务是需要监听手机是否至于后台,比方说定时考试、倒计时秒杀、唤醒后回传最新定位。
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);
}
}