javascript – How can I know the active time of the web?

Question:

How can I know in JavaScript how long a page that is NOT in focus, but open, has taken? I mean, it has it open but is browsing others, how can I know how long it has been since mine has been focused?

Answer:

You can do this with the Page Visibility API . With that API you can get information about whether the page is visible / focused or not. So what you would do would be:

  1. Create a Visibility Change Event Handler
  2. If the page has lost visibility / focus:
    1. Save current time to variable
  3. If the page has gained visibility / focus:
    1. Read the current time
    2. Compare with saved time
    3. Take actions according to values

Here's an example of how it would be based on the demo on the MDN page for the Page Visibility API :

 // Especificar el nombre de la propiedad hidden y del evento de cambio para la visibilidad var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { // Opera 12.10 y Firefox 18 hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } var horaEscondida = ""; var horaActual = ""; // Si la pagina se esconde, guarda la hora // Si la pagina se muestra, compara horas function handleVisibilityChange() { if (document[hidden]) { horaEscondida = Date.now(); } else { var horaActual = Date.now(); console.log("Me escondiste durante " + Math.floor((horaActual - horaEscondida) / 1000) + " segundos"); } } // Muestra mensaje en la consola si el navegador no soporta addEventListener o la Page Visibility API if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") { console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API."); } else { // Controlador de cambios de visibilidad en la pagina document.addEventListener(visibilityChange, handleVisibilityChange, false); }

One reason for using this API is that the focus and blur events on the window can fail and / or give false positives. For example: If the user opens the JS console, the window will be considered to have lost focus even when the user is still in it (although depending on what you want, that may be worth it).

Also, not all browsers support them; for example: on iPad / iPhone there are pageShow / pageHide events instead of focus and blur for the page. Which could lead to some issues on mobile devices.

One option would be to extend the code above to use Page Visibility and if it doesn't work or isn't available, move on to the focus / blur solution.

Scroll to Top