简体   繁体   中英

onblur and onfocus event but using iframes

I am creating an app that will communicate from one computer to another when the other person is looking at the window. For example imagine you are chatting with someone on facebook chat and the other person changes tab, or alt+tabs or something - the other person would know (not the specifics, just that the facebook window wasnt on top and active).

This was, eventually, easy:

/**
*   Functions which keeps track of whether the page is the active tab
*   this reports back to the host
*/
window.onblur=function(){
    if(conn!=null) {
        conn.send(JSON.stringify({'type':'upd','ele':'vis','status':0}));
    }
    make_noise('0000');
};
window.onfocus=function(){  // when you focus the window
    if(conn != null) {
        conn.send(JSON.stringify({'type':'upd','ele':'vis','status':1}));
    }
    stop_noise('0000');
};

This all works, no problem.

However I also have an iframe on the page. When the user is IN the iframe then the onblur event is triggered and it looks like the user alt+tabbed, went to another tab etc.

I tried this to resolve:

window.onblur=function(){   // when you leave the window
    if(conn != null && (document.activeElement != document.getElementById("content_frame"))) {      
            conn.send(JSON.stringify({'type':'upd','ele':'vis','status':0}));
        }
    }
    make_noise('0000');
};

However because the iframe stays the activeElement, irrespective of if the window is currently active, this causes a false positive to fire.

Can anybody think of a way around this? $('iframe').is(':focus') was suggested as a way of testing the focus of the iframe but then it works just the same as with activeElement...

Thanks so much, Alex

You can check like this. i have used jquery btw in my code.

$(window).blur(function () {
  if ($('iframe').is(':focus')) {
    ...
  } else {
   ...
  }                
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM