标题解释了自己.如何检测网页是否已进入后台?
我正在实现一个聊天应用程序,我将使用此信息来决定显示新的消息通知.我想GMail会使用类似的东西.如果页面位于背景上,则显示桌面通知(在chrome上),如果不显示则不显示.
解决方法@H_301_6@
我知道答案已经被选中,但我想分享另一种方式.
您可以在文档上使用hasFocus方法来查看它是否具有焦点.没有理由设置自己的变量.
这是概念代码的一些证明. jsFiddle位于底部.每3秒钟它将检查窗口是否有焦点 – 显示是或否.
HTML:
<p>This will show if the document has focus every three seconds</p>
<button id="go">Go</button>
<button id="stop">Stop</button>
<ul id="active_log">
</ul>
CSS:
#stop { display: none; }
文档准备好的Javascript里面:
var timeout = null;
var checkActive = function() {
var isActive = window.document.hasFocus(),$activity = $("<li />").text(isActive.toString());
$('#active_log').prepend($activity).find('li:nth-child(n+6)').fadeOut(function() {
$(this).remove();
});
timeout = setTimeout(checkActive,3000);
}
$('#go').click(function() {
$(this).hide().siblings('button').show();
checkActive();
});
$('#stop').click(function() {
$(this).hide().siblings('button').show();
clearTimeout(timeout);
timeout = null;
});
您可以在文档上使用hasFocus方法来查看它是否具有焦点.没有理由设置自己的变量.
这是概念代码的一些证明. jsFiddle位于底部.每3秒钟它将检查窗口是否有焦点 – 显示是或否.
HTML:
<p>This will show if the document has focus every three seconds</p> <button id="go">Go</button> <button id="stop">Stop</button> <ul id="active_log"> </ul>
CSS:
#stop { display: none; }
文档准备好的Javascript里面:
var timeout = null; var checkActive = function() { var isActive = window.document.hasFocus(),$activity = $("<li />").text(isActive.toString()); $('#active_log').prepend($activity).find('li:nth-child(n+6)').fadeOut(function() { $(this).remove(); }); timeout = setTimeout(checkActive,3000); } $('#go').click(function() { $(this).hide().siblings('button').show(); checkActive(); }); $('#stop').click(function() { $(this).hide().siblings('button').show(); clearTimeout(timeout); timeout = null; });