简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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