如何使用jquery / javascript检测页面是背景还是前景? [英] How can it be detected if a page is on background or foreground with jquery/javascript?

查看:63
本文介绍了如何使用jquery / javascript检测页面是背景还是前景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题解释了自己。如何检测网页是否已进入后台?

The title explains itself. How can I detect if a web page has gone to background?

我正在实施聊天应用程序,我将使用此信息来决定显示新的消息通知。我想GMail会使用类似的东西。如果页面在背景上,它会显示桌面通知(在chrome上),如果没有,则显示它们。

I'm implementing a chat application and I'll use this information to decide showing new message notifications. I suppose that GMail uses something like that. If the page is on background, it shows desktop notifications (on chrome), if not it doesn't show them.

推荐答案

我知道答案已被选中,但我想分享另一种方式。

I know that the answer has already been selected but I wanted to share another way.

你可以使用 hasFocus 文档上的方法,看它是否有焦点。没有理由设置自己的变量。

You can use the hasFocus method on the document to see if it has the focus. There is no reason to set your own variable.

以下是概念代码的一些证明。 jsFiddle位于底部。每隔3秒,它会检查窗口是否有焦点 - 显示真或假。

Here's some proof of concept code. jsFiddle is at the bottom. Every 3 seconds it will check if the window has focus or not–displaying true or false.

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:

Javascript inside on document ready:

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;
});

http://jsfiddle.net/natedavisolds/2D7za/1/

这篇关于如何使用jquery / javascript检测页面是背景还是前景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆