问题
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:
test.html:
<!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>
test1.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);
doc.ready(function(){
win.focus(function() { console.log('Focus'); });
win.blur(function() { console.log('Blur'); });
doc.mousemove(function() { console.log('Move'); });
});
</script></body></html>
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.
回答1:
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'); };
回答2:
The answer appears to be in the instance of jQuery. In your example, you're attaching an event handler on an element in top, using the instance of jQuery in the iframe. This is only a guess, but I'd say that the 'magic' doesn't translate across instances of jQuery.
Try this instead:
var doc = window.top.$(window.top.document);
var win = window.top.$(window.top);
doc.ready(function(){
win.focus(function() { console.log('Focus'); });
win.blur(function() { console.log('Blur'); });
doc.mousemove(function() { console.log('Move'); });
});
Realisation gleamed from:
https://leapinggorilla.com/Blog/Read/4/passing-messages-to-iframes-with-jquery
来源:https://stackoverflow.com/questions/12325519/using-jquery-to-attach-a-listener-to-top-window-focus-events-inside-an-iframe