Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between document.hidden vs document.hasFocus()

Please explain the difference between document.hidden , the HTML5 Page Visibility API and document.hasFocus(). I am doing a project which pops HTML5 Desktop Notification when the tab is not focused. I am kind of confused which one to use.

like image 873
Amerrnath Avatar asked Mar 29 '15 16:03

Amerrnath


2 Answers

The hidden attribute is defined like this:

On getting, the hidden attribute MUST return true if the Document contained by the top level browsing context (root window in the browser's viewport) is not visible at all. The attribute MUST return false if the Document contained by the top level browsing context is at least partially visible on at least one screen.

If the defaultView of the Document is null, on getting, the hidden attribute MUST return true.

The hasFocus method is defined like this

The hasFocus() method on Document objects must return true if the Document's browsing context is focused, and all its ancestor browsing contexts are also focused, and the top-level browsing context has the system focus. If the Document has no browsing context or if its browsing context has no top-level browsing context, then the method will always return false.

For example, if you open a page in a foreground tab, and then open another window, the tab will (or may) still be partially visible, so hidden returns false. However, the new window has focus, so hasFocus() returns false for the tab.

If you run the following snippet, the document inside the iframe will be visible but won't have focus (this stackoverflow page is focused instead):

document.body.innerHTML = 
  '<p>hidden: ' + document.hidden + '</p>' +
  '<p>hasFocus: ' + document.hasFocus() + '</p>';

But in this other one, since you click the button inside the iframe, it is both visible and focused:

document.getElementsByTagName('input')[0].onclick = function() {
  document.body.innerHTML = 
    '<p>hidden: ' + document.hidden + '</p>' +
    '<p>hasFocus: ' + document.hasFocus() + '</p>';
};
<input type="button" value="Click me!" />
like image 184
Oriol Avatar answered Sep 29 '22 00:09

Oriol


TLDR:

document.hidden: returns true if web-app is running and is not at all VISIBLE

document.hasFocus(): returns true if the tab is currently running and the tab is focused in the browser

like image 38
Gabriel Petersson Avatar answered Sep 29 '22 00:09

Gabriel Petersson