4

I would like to check if my website is in foreground with JavaScript. But don't answer before reading everything because you would directly say to me that I should do this:

$(window)
    .focus(function() {
        console.log("focus");
    })
    .blur(function() {
        console.log("blur");
    });​

But the problem is that I've got an iframe from a third party on my page and if the user clicks on the iframe the window blur event gets fired but the user is acctualy still on my page. I tried to fix this by checking if document.activeElement is an iframe on blur:

$(window)
    .focus(function() {
        console.log("focus");
    })
    .blur(function() {
        console.log("blur");
        if (document.activeElement.tagName.toLowerCase() == "iframe") {
            console.log("still focus");
        }
    });​

The problem here is that I'm not able to check if the page is not in foreground anymore when a user clicks on the iframe first and then on another application.

So how can I check if the site is in foreground when it got an iframe in it?

noob
  • 8,982
  • 4
  • 37
  • 65

1 Answers1

3

You should be able to use the Page Visibility API.

This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.

Learn more

Example

Community
  • 1
  • 1
gearsdigital
  • 13,915
  • 6
  • 44
  • 73
  • This would cover the problem for the modern browsers but I also need IE8 support. – noob Aug 29 '12 at 20:51
  • Did you heard about graceful degradation? http://stackoverflow.com/a/9634295/294076 – gearsdigital Aug 29 '12 at 21:09
  • No but what that guy is doing is awesome. The source really looks like that it should work but I haven't tested it yet. – noob Aug 29 '12 at 21:45