主动 window 检测

Active window detection

I am checking that the current tab/window is focused or not to perform some particular task.The following function is correctly working to detect the focus when i am switching tabs but when the tab is open and我打开一个软件(音乐player/windows文件夹)保持标签active/open,功能仍然认为window/tab是重点!我试图实现的情况是检测window/tab 由于在当前焦点 window/tab 上打开 application/software 而失去了焦点。如果你根据我的代码提供一个带有你的答案的 jsfiddle 会很棒!

$(document).ready(function() {

        var hidden, change, vis = {
            hidden: "visibilitychange",
            mozHidden: "mozvisibilitychange",
            webkitHidden: "webkitvisibilitychange",
            msHidden: "msvisibilitychange",
            oHidden: "ovisibilitychange" /* not currently supported */
        };             
    for (hidden in vis) {
        if (vis.hasOwnProperty(hidden) && hidden in document) {
            change = vis[hidden];
            break;
        }
    }
    if (change)
        document.addEventListener(change, onchange);
    else if (/*@cc_on!@*/false) // IE 9 and lower
        document.onfocusin = document.onfocusout = onchange
    else
        window.onfocus = window.onblur = onchange;

    function onchange (evt) {
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin")
           window_focus = true;
        else if (evt.type == "blur" || evt.type == "focusout")
           window_focus = false;
        else        
           window_focus = this[hidden] ? false : true;
    }

});

帧数:

<frameset rows="130,*" style="border: 1px #CC3333"  noresize="noresize" ">
<frame name="showcountframe" src="https://jsfiddle.net/nvobhaor/1/" scrolling=no marginheight="2" marginwidth="2"  noresize="noresize">
<frame name="showcontframe" src="showcontframe.html" marginheight="0" marginwidth="0" noresize="noresize">
</frameset><noframes></noframes>

您可以为此使用 window.onfocuswindow.onblur 而不是那堵代码墙。它受到所有主要浏览器的支持,并且可以完美地满足您的需求。例如,它会检测您何时更改选项卡,或按您所说打开另一个应用程序。

示例:

window.onfocus = function() {
    console.log('Focused');
};

window.onblur = function() {
    console.log('Not focused');
};