Oleg Barshay Oleg Barshay - 1 year ago 135
Javascript Question

Using jQuery to attach a listener to top window focus events inside an iframe

Is there a way to attach a listener inside an iFrame that will get called when the browser window gets focus (tab or title bar gets clicked)? Here's the test code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><body><iframe src="test1.html"></iframe></body></html>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script></head><body><script type="text/javascript">
var doc = $(window.top.document);
var win = $(window.top);
win.focus(function() { console.log('Focus'); });
win.blur(function() { console.log('Blur'); });
doc.mousemove(function() { console.log('Move'); });

Hitting test.html, mousemove listener gets called but focus and blur only gets called when the iFrame is clicked on and off but not when the browser window gets/loses focus. I've tried attaching the listener to doc and win with the same result. I am testing in Chrome and Firefox.

Answer Source

I really have no idea, what's the magic of jQuery's focus/blur is, but I believe that magic is a bit buggy. (or it's maybe a feature that I dont't know :o)

If you doing it without jQuery methods, it works fine.

var doc = window.top.document;
var win = window.top;
win.onfocus = function() { console.log('Focus'); };
win.onblur  = function() { console.log('Blur'); };
doc.onmousemove = function() { console.log('Move'); };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download