如何知道Chrome窗口何时具有焦点(并且文档中有一个插件)

How to know when the Chrome window has the focus (and there's a plugin in the document)?

本文关键字:文档 有一个 插件 Chrome 何知道 窗口 何时具 焦点      更新时间:2023-09-26

我有一个应用程序,当它不处理键盘事件时,需要通知它的用户。我一直在监控document.hasFocus(),这些在Firefox和IE(!)中可以正常工作,但在Chrome中却没有。

如果我从地址栏开始,document.hasFocus()返回 false;当我 TAB 时,包含插件实例的文档获得焦点,document.hasFocus()返回 true;现在,如果我再次 TAB,插件(在本例中为 Silverlight)将获得焦点,document.hasFocus()返回 false。

也许这是正确的行为,而其他两个浏览器错误地返回 true,但如果是这种情况,我怎么知道浏览器窗口何时具有焦点?

你可以这样尝试:

var hasFocus = false,
    toggleFocus = function() {
        hasFocus = !hasFocus
    };
window.addEventListener( 'focus', toggleFocus );
window.addEventListener( 'blur', toggleFocus );