/**
* 監聽瀏覽器標簽頁的顯示與隱藏
*/
class ListenerPageVisibility {
constructor () {
// 設置隱藏屬性和改變可見屬性的事件的名稱
this.hidden = ''
this.visibilityChange = ''
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
this.hidden = "hidden"
this.visibilityChange = "visibilitychange"
} else if (typeof document.msHidden !== "undefined") {
this.hidden = "msHidden"
this.visibilityChange = "msvisibilitychange"
} else if (typeof document.webkitHidden !== "undefined") {
this.hidden = "webkitHidden"
this.visibilityChange = "webkitvisibilitychange"
}
this.handleChange = (callBackHidden, callBackVisibility) => {
if (document[this.hidden]) {
// 頁面是隱藏狀態
callBackHidden && callBackHidden()
} else {
// 頁面是展示狀態
callBackVisibility && callBackVisibility()
}
}
}
/**
* 全局訪問點
* @param callBackHidden 頁面隱藏執行的回調方法
* @param callBackVisibility 頁面顯示執行的回調方法
*/
linsternVisibility (callBackHidden, callBackVisibility) {
// 如果瀏覽器不支持addEventListener 或 Page Visibility API 給出警告
if (typeof document.addEventListener === "undefined" || typeof document[this.hidden] === "undefined") {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.")
} else {
// 處理頁面可見屬性的改變
document.addEventListener(this.visibilityChange, () => {
this.handleChange(callBackHidden, callBackVisibility)
}, false)
}
}
}
// 調用實例
let navChange = new ListenerPageVisibility()
navChange.linsternVisibility(
// 頁面是隱藏狀態執行方法
() => {
// TODO 瀏覽器標簽頁處於隱藏狀態時,執行的方法
},
// 頁面是可見狀態執行方法
() => {
// TODO 瀏覽器標簽頁處於顯示狀態時,執行的方法
}
)