问题
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 i open a software(music player/windows folders) keeping the tab active/open, the function still consider the window/tab as focused!The situation that i am trying to achieve is to detect that the window/tab is lost the focus due to opening application/software upon currently focused window/tab.It will be great if you provide a jsfiddle with your answer based on my code!
$(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;
}
});
Frame:
<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>
回答1:
You could use window.onfocus and window.onblur for this instead of that wall of code. It is supported by all the main browsers and works perfectly fine for the purpose you want. It detects when you change tabs, for example, or open another application as you said.
Example:
window.onfocus = function() {
console.log('Focused');
};
window.onblur = function() {
console.log('Not focused');
};
来源:https://stackoverflow.com/questions/29720294/active-window-detection