Check if windows/page/document/iframe has focus

2019-07-21 08:57发布

问题:

I've asked a similar question already, but I need it for a more specific case so I decided to make a new question to don't mix things up.

Check if window has focus

1. I'm making a PTC site, where users get paid by visiting sites for x seconds.
2. The ad view works like this: A new page is opened, containing two things, the top bar with the counter and the iframe which contains the advertiser's site).
3. I want to force the user to see that page for the x seconds that the advertiser paid for.
4. To check if the user is seeing the page, IMO, I need to check if either the document or iframe has focus.

Problems:
1. I can't use window.onblur or window.onfocus since the user can lose focus before the page loads and bypass those commands.
2. I can't use hasFocus() on the iframe because Chrome throws this error: Blocked a frame with origin "xxx" from accessing a frame with origin "yyy". Protocols, domains, and ports must match.

I know two similar sites that accomplish this, but their javascript is so weird that I can't understand a single line. (neobux.com and clixsense.com)

I'm going crazy on this because I've tried so many things and none of them worked, I really need help on this.
Thanks!

回答1:

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.