如何使用 Javascript 在 Chrome 中检测标签是否处于焦点状态? [英] How to detect when a tab is focused or not in Chrome with Javascript?

查看:34
本文介绍了如何使用 Javascript 在 Chrome 中检测标签是否处于焦点状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道用户当前是否正在 Google Chrome 中查看标签页.我尝试使用绑定到窗口的事件模糊和焦点,但似乎只有模糊才能正常工作.

I need to know if the user is currently viewing a tab or not in Google Chrome. I tried to use the events blur and focus binded to the window, but only the blur seems to be working correctly.

window.addEventListener('focus', function() {
  document.title = 'focused';
});

window.addEventListener('blur', function() {
  document.title = 'not focused';
});

焦点事件很奇怪,只是有时.如果我切换到另一个选项卡并返回,则不会激活焦点事件.但是如果我点击地址栏然后返回页面,它会.或者,如果我切换到另一个程序,然后返回到 Chrome,它会在当前处于焦点状态的选项卡上激活.

The focus event works weird, only sometimes. If I switch to another tab and back, focus event won't activate. But if I click on the address bar and then back on the page, it will. Or if I switch to another program and then back to Chrome it will activate if the tab is currently focused.

推荐答案

2015 更新: 带有可见性 API 的新 HTML5 方式(摘自 Blowsie 的评论):

2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):

document.addEventListener('visibilitychange', function(){
    document.title = document.hidden; // change tab text for demo
})

<小时>

原始海报提供的代码(在问题中)现在有效,截至 2011 年:


The code the original poster gives (in the question) now works, as of 2011:

window.addEventListener('focus', function() {
    document.title = 'focused';
});

window.addEventListener('blur', function() {
    document.title = 'not focused';
});

编辑:几个月后在 Chrome 14 中,这仍然有效,但用户必须至少点击窗口中的任意位置一次与页面交互.仅仅滚动等不足以完成这项工作.执行 window.focus() 也不会自动执行此操作.如果有人知道解决方法,请提及.

edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus() does not make this work automatically either. If anyone knows of a workaround, please mention.

这篇关于如何使用 Javascript 在 Chrome 中检测标签是否处于焦点状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆