Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to check if the user has windows on focus, I'm currently doing this:

var isonfocus=true;  
window.onblur = function(){  
  isonfocus=false;  
}  
window.onfocus = function(){  
  isonfocus=true;  
}

And whenever I need to check if the user has the windows on focus I just do if(isonfocus==true).

Problem: if the user loses focus before the page loads, even if I do if(isonfocus==true) it will return true, even though the window is not on focus, and defining the var to false var isonfocus=false; will do the reverse.

Can someone help me? Thanks.

UPDATE
Imagine a PTC (Paid-To-Click) site, when you go and click an ad to view, most sites verify if the user is actually seeing the advertiser site (has focus) or not (lost focus).
This is similar with what I need, I need a way to verify if the user has the window (which contains an iframe) on focus.
And to gain focus, the user could click the iframe, document or on the tab.
And please note that this needs to work on all major browsers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

Why not use the hasFocus method e.g.

if (document.hasFocus()) {
    ...
}

If you need to handle iframe's as well then your check just becomes either or e.g.

function isFocused() {
    return document.hasFocus() || document.getElementById('iframe').contentWindow.document.hasFocus();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...