检查页面的页面可见性和页面焦点

Checking Page Visibility and Page Focus for a page

我想确定用户何时在页面上。

因此,当用户单击另一个 window(失去焦点)或更改选项卡时,我应该停止在我的页面上播放视频。

问题在于尝试同时执行这两项操作。

例如,通过这个JS插件(JQuery Visbility),我可以检查我的页面tab/window是否打开。

这是它的工作原理:

$(document).on({
          'show': function() {
            console.log('The page gained visibility; the `show` event was triggered.');
          },
          'hide': function() {
            console.log('The page lost visibility; the `hide` event was triggered.');
          }
        });

但是无法检测页面是否有焦点。例如,该页面可能已打开,但我可能会单独打开另一个 window 并将注意力集中在该页面上。

以下代码负责处理(取自 here):

function check()
{
    if(document.hasFocus() == lastFocusStatus) return;

    lastFocusStatus = !lastFocusStatus;
    statusEl.innerText = lastFocusStatus ? 'with' : 'without';
}

window.statusEl = document.getElementById('status');
window.lastFocusStatus = document.hasFocus();

check();
setInterval(check, 200);

现在,我正在尝试同时进行这两项工作。可能吗?

您可以为 windowfocusblur 事件添加事件侦听器。

var hasFocus = true;
$(window).focus(function(){
   hasFocus = true;
});
$(window).blur(function(){
   hasFocus = false;
});
//check the hasFocus variable to see if the window has focus