jQuery 检查窗口是否有焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17389280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if window has focus
提问by James
I need to check if the user has windows on focus, I'm currently doing this:
我需要检查用户是否有焦点窗口,我目前正在这样做:
var isonfocus=true;
window.onblur = function(){
isonfocus=false;
}
window.onfocus = function(){
isonfocus=true;
}
And whenever I need to check if the user has the windows on focus I just do if(isonfocus==true)
.
每当我需要检查用户是否将窗口放在焦点上时,我都会这样做if(isonfocus==true)
。
Problem: if the user loses focus before the page loads, even if I do
if(isonfocus==true)
it will return true, even though the window is not on focus, and defining the var to false var isonfocus=false;
will do the reverse.
问题:如果用户在页面加载之前失去焦点,即使我这样做
if(isonfocus==true)
也会返回 true,即使窗口不在焦点上,并且将 var 定义为 falsevar isonfocus=false;
将执行相反的操作。
Can someone help me? Thanks.
有人能帮我吗?谢谢。
UPDATE
Imagine a PTC (Paid-To-Click) site, when you go and click an ad to view, most sites verify if the user is actually seeing the advertiser site (has focus) or not (lost focus).
This is similar with what I need, I need a way to verify if the user has the window (which contains an iframe) on focus.
And to gain focus, the user could click the iframe, document or on the tab.
And please note that this needs to work on all major browsers.
更新
想象一下 PTC(点击付费)网站,当您点击一个广告进行查看时,大多数网站都会验证用户是否实际看到了广告商网站(有焦点)或没有(失去焦点)。
这与我需要的类似,我需要一种方法来验证用户是否将窗口(包含 iframe)放在焦点上。
为了获得焦点,用户可以单击 iframe、文档或选项卡。
请注意,这需要适用于所有主要浏览器。
采纳答案by Dhirish
var has_focus = true;
function loading_time() {
$(":focus").each(function() {
if($(this).attr("id")=="iframeID") has_focus = true;
});
if(has_focus==true) alert('page has focus');
else alert('page has not focus');
setTimeout("loading_time()", 2000);
}
window.onblur = function(){
has_focus=false;
}
window.onfocus = function(){
has_focus=true;
}
$(window).load(function(){
setTimeout("loading_time()", 2000);
});
To make it more efficient, you need to var has_focus = false;
and make the user click somewhere on the page.
为了提高效率,你需要var has_focus = false;
让用户点击页面上的某个地方。
回答by James
Why not use the hasFocusmethod e.g.
为什么不使用hasFocus方法,例如
if (document.hasFocus()) {
...
}
If you need to handle iframe
's as well then your check just becomes either or e.g.
如果您还需要处理iframe
's 那么您的支票就变成要么或例如
function isFocused() {
return document.hasFocus() || document.getElementById('iframe').contentWindow.document.hasFocus();
}
回答by Dhirish
You can use document.visibilityState
to know whether the page is in focus or not.
您可以使用它document.visibilityState
来了解页面是否处于焦点状态。
回答by SpYk3HH
Cross Browser jQuery Solution!The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:
跨浏览器 jQuery 解决方案!以下插件将通过您对各种版本的 IE、Chrome、Firefox、Safari 等的标准测试,并相应地建立您声明的方法。它还处理以下问题:
- timers! ewwww!
- onblur|.blur/onfocus|.focus "duplicate" calls
- window losing focus through selection of alternate app, like word
- This tends to be undesirable simply because, if you have a bank page open, and it's onblurevent tells it to mask the page, then if you open calculator, you can't see the page anymore!
- Not triggering on page load
- 计时器!哇!
- onblur|.blur/onfocus|.focus “重复”调用
- 窗口通过选择替代应用程序失去焦点,例如 word
- 这往往是不可取的,因为,如果您打开了一个银行页面,并且它的onblur事件告诉它屏蔽该页面,那么如果您打开计算器,您将无法再看到该页面!
- 页面加载时不触发
Use is as simple as:
使用非常简单:
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
});
// OR Pass False boolean, and it will not trigger on load,
// Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
console.log("Combo\t\t", event, isVisible);
}, false);
// OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
// (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
blur: function(event) {
console.log("Blur\t\t", event);
},
focus: function(event) {
console.log("Focus\t\t", event);
}
});
// OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
console.log("Blur\t\t", event);
},
function(event) {
console.log("Focus\t\t", event);
});
New&improvedversion,madeforbothvanillaandjQueryfoundhere!
New&improvedversion,madeforbothvanillaandjQueryfoundhere!
/* Begin Plugin */
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);
/* End Plugin */
// Simple example
$(function() {
$.winFocus(function(event, isVisible) {
$('td tbody').empty();
$.each(event, function(i) {
$('td tbody').append(
$('<tr />').append(
$('<th />', { text: i }),
$('<td />', { text: this.toString() })
)
)
});
if (isVisible)
$("#isVisible").stop().delay(100).fadeOut('fast', function(e) {
$('body').addClass('visible');
$(this).stop().text('TRUE').fadeIn('slow');
});
else {
$('body').removeClass('visible');
$("#isVisible").text('FALSE');
}
});
})
body { background: #AAF; }
table { width: 100%; }
table table { border-collapse: collapse; margin: 0 auto; width: auto; }
tbody > tr > th { text-align: right; }
td { width: 50%; }
th, td { padding: .1em .5em; }
td th, td td { border: 1px solid; }
.visible { background: #FFA; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>See Console for Event Object Returned</h3>
<table>
<tr>
<th><p>Is Visible?</p></th>
<td><p id="isVisible">TRUE</p></td>
</tr>
<tr>
<td colspan="2">
<table>
<thead>
<tr>
<th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>
</tr>
</thead>
<tbody></tbody>
</table>
</td>
</tr>
</table>
回答by intuitivepixel
回答by bkucera
If the user has the browser window focused/active, but has just clicked the refresh button (or url bar, etc), document.hasFocus()
will tell you the window is not active.
如果用户已聚焦/激活浏览器窗口,但刚刚单击了刷新按钮(或 url 栏等),document.hasFocus()
则会告诉您该窗口未处于活动状态。
However, you can call window.focus()
and see if the focus
event is actually fired. If it is, the browser is still focused/active.
但是,您可以调用window.focus()
并查看focus
事件是否真的被触发。如果是,则浏览器仍处于焦点/活动状态。
const windowHasFocus = function () {
if (document.hasFocus()) return true
let hasFocus = false
window.addEventListener('focus', function () {
hasFocus = true
})
window.focus()
return hasFocus
}