Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.hasFocus() for chrome

Does anyone know what to use instead of hasFocus() for Chrome? I want to know when my Chrome tab has focus or not, so I can blink an alert message in the title.

Cheers

like image 303
sudopal Avatar asked Aug 16 '26 10:08

sudopal


2 Answers

You could listen for the onfocus/onblur events and keep track of page state that way.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="output">
    </div>
    <script>
      var has_focus = true;

      function print(str) {
        var out = document.getElementById('output')      
        out.innerText = out.innerText + "\n" + str;
      };

      window.onfocus = function() {
        print('focus');
        has_focus = true;
      };

      window.onblur = function() {
        print('blur');
        has_focus = false;
      };
    </script>
  </body>
</html>
like image 198
Arne Roomann-Kurrik Avatar answered Aug 19 '26 00:08

Arne Roomann-Kurrik


The page visibility API should do the trick: https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API

document.hidden

Returns true if the page is in a state considered to be hidden to the user, and false otherwise.

Of course, since this is a new API, you'll need to use different browser prefixes:

if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
    hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
}
var isHidden = document[hidden];
// or even
var isFocused = !isHidden;
like image 23
Kevin Lamping Avatar answered Aug 18 '26 23:08

Kevin Lamping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!