Skip to content
Advertisement

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.

Advertisement

Answer

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!" />
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement