简体   繁体   English

如何知道浏览器选项卡是否在加载Javascript时关注?

[英]How to know if a browser tab focused when it's loaded with Javascript?

There is a similar question here . 还有一个类似的问题在这里 But it doesn't work when a page is initially loaded because the blur event will not fire if for example the user opens the page in a new tab and it doesn't get focus. 但是在最初加载页面时它不起作用,因为如果例如用户在新选项卡中打开页面并且它没有获得焦点,则模糊事件将不会触发。

So what would be the best way to do this? 那么最好的方法是什么呢?

For now, my temporary solution is to assume the tab is blurred when it loads and bind a function to the mouseover event of the document that will set it to focused. 目前,我的临时解决方案是假设选项卡在加载时模糊,并将函数绑定到文档的鼠标悬停事件,将其设置为焦点。 But that won't work if the user does not have their mouse on the page. 但是,如果用户没有在页面上放置鼠标,那将无效。

Borrowing from the code you linked to, set the default to blurred: 借用您链接的代码,将默认值设置为模糊:

<div id="blurDiv"></div>

<script>

var updateStatus = (function() {

  // Private stuff
  var el = document.getElementById('blurDiv');

  // The updateStatus function
  return function (evt) {
    evt = evt || window.event;
    var evtType = evt.type;
    var state;

    // Determine state
    if (evtType == 'load' || evtType == 'blur' || evtType == 'focusout' ) {
      state = 'blurred';
    } else {
      state = 'focussed';
    }

    // Now do something...
    el.innerHTML += '<br>' + state
  };
})();

window.onload = updateStatus;

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = updateStatus;
    document.onfocusout = updateStatus;
} else {
    window.onfocus = updateStatus;
    window.onblur = updateStatus;
}

</script>

IE seems to fire lots of extra events, every time something gets focus, there is first a blur then a focus so clicking on things in the page has lots of spurious blur/focus pairs. IE似乎会引发很多额外的事件,每当有东西聚焦时,首先会出现模糊然后焦点,因此点击页面中的内容会产生大量的虚假模糊/焦点对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM