Search code examples
javascriptjqueryforeground

Check if site is in foreground


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?


Solution

  • 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