4

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!

Community
  • 1
  • 1
  • There are many reasons why you could be getting the error in Chrome, however, that's not to say you can't fix it - see this [answer](http://stackoverflow.com/questions/14892556/facebook-unsafe-javascript-issue-document-domain-values-should-be-same). Effectively all it's doing is trying to protect you from a *potential* XSS attack, I am pretty sure you can force the browser to ignore the error and continue. – James Jul 15 '13 at 15:26
  • I want to pay someone to code a script to accomplish this. How should I proceed? –  Jul 22 '13 at 18:14
  • 1) go to http://freedomsponsors.org/ and create an account 2) click on sponsor a new issue, check the 'Check if you want to create a personal request, unrelated to any open source project' checkbox 3) describe your problem and set your bounty 4) advertise – Tony Lâmpada Sep 17 '13 at 14:13

1 Answers1

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.