Window and iframe hasFocus not working

Discussion in 'JavaScript' started by WebProgrammer11, Oct 8, 2011.

  1. #1
    Hi there,

    I'm trying to check whether the current window or iframe has the focus and only run down a counter if this is the case. However, the hasFocus() function seems not to work for the window and iframe object in some browsers. My current script looks like this:


    function updateAdStatus(adKey, adId) {
    if(document.hasFocus() || window.frames['ad_iframe'].document.hasFocus()) {
    document
    .getElementById("adSec").innerHTML = parseInt(document.getElementById("adSec").innerHTML-1);
    }
    }

    if(parseInt(document.getElementById("adSec").innerHTML) == 0) {
    initAdStatus
    (adKey, adId);
    }else{
    setTimeout
    ("updateAdStatus("+adKey+", "+adId+")", 1000);
    }
    }

    If anyone could help me out on how to get this to work, it would be much appreciated!

    Thanks in advance.

    Cheers.
     
    WebProgrammer11, Oct 8, 2011 IP
  2. gumape

    gumape Peon

    Messages:
    30
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,

    you are right, the hasFocus method is not supported in Opera.
    A possible workaround is that to listen the onfocus and onblur events on the window object in Opera:

    <html>
    <head>
    <script type="text/javascript">
    	function updateInfo (message) {
    		var input = document.getElementById ("info"); 
    		info.value = message;
    	}
    	function onFocus () {
    		updateInfo ('focus');
    	}
    	function onBlur () {
    		updateInfo ('blur');
    	}
    
    		// opera
    	if (!window.document.hasFocus) {
    		window.onfocus = onFocus;
    		window.onblur = onBlur;
    	}
    </script>
    </head>
    <body>
    	<input id="info" />
    </body>
    </html>
    Code (markup):
     
    gumape, Oct 14, 2011 IP
  3. gumape

    gumape Peon

    Messages:
    30
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I forgot to mention that the onfocus and onblur events need to be listen on both window objects (see contentWindow).
     
    gumape, Oct 14, 2011 IP