Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - Check if window has focus

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

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

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...