音樂或音效常常會持續播放,儘管瀏覽器已經在背景模式。
利用這個小工具偵測網頁目前是否正被使用,並暫停網站的一些功能。
See the Pen PSpageFocusDetection by Monkianer (@monkianer) on CodePen.
var pageFocusDetection = {
interval: null,
init: function(){
this.add();
},
focusInAction: function(){
},
focusOutAction: function(){
},
checkPageFocus: function() {
var _this = pageFocusDetection;
if ( document.hasFocus() ) {
_this.focusInAction();
} else {
_this.focusOutAction();
}
},
add: function(){
pageFocusDetection.interval = setInterval( pageFocusDetection.checkPageFocus, 200 );
},
remove: function(){
clearInterval( pageFocusDetection.interval );
}
}
用法
pageFocusDetection.focusInAction = function(){
// 正在使用時才需要的動作,例如:音效
};
pageFocusDetection.focusOutAction = function(){
// 不在使用時要停止的動作,例如:音效
};
// 初始
pageFocusDetection.init();