检查站点是否在前台
我想通过JavaScript检查我的网站是否在前台。 但是在阅读所有内容之前不要回答,因为你会直接对我说我应该这样做:
$(window) .focus(function() { console.log("focus"); }) .blur(function() { console.log("blur"); });
但问题是我的页面上有来自第三方的iframe,如果用户点击iframe,窗口模糊事件会被触发,但用户仍然在我的页面上。 我试图通过检查document.activeElement
是否为模糊的iframe来解决此问题:
$(window) .focus(function() { console.log("focus"); }) .blur(function() { console.log("blur"); if (document.activeElement.tagName.toLowerCase() == "iframe") { console.log("still focus"); } });
这里的问题是,当用户先点击iframe然后再点击另一个应用程序时,我无法再检查页面是否不在前台。
那么如果网站中有iframe,我如何检查网站是否在前台?
您应该能够使用Page Visibility API 。
此规范定义了一种方法,供站点开发人员以编程方式确定页面的当前可见性状态,以便开发function和CPU高效的Web应用程序。
学到更多
- http://davidwalsh.name/page-visibility
- https://developers.google.com/chrome/whitepapers/pagevisibility