--- title: Page Visibility API slug: Web/API/Page_Visibility_API tags: - API - DOM - Intermediário - Tutoriais translation_of: Web/API/Page_Visibility_API ---
A Page Visibility API permite-lhe saber quando uma página da Web está visível ou em foco. Com a navegação por separadores, existe uma chance razoável de que qualquer página da Web esteja em segundo plano e, portanto, não seja visível para o utilizador. Quando o utilizador minimiza a página da Web ou move-se para outro separador, a API envia um evento {{event('visibilitychange')}} sobre a visibilidade da página. Pode detetar o evento e executar algumas ações ou comportar-se de forma diferente. Por exemplo, se a sua aplicação da Web estiver a reproduzir um vídeo, esta pausará o momento em que o utilizador olha para outro navegador, e reproduz novamente quando o utilizador volta ao separador. O utilizador não perde o seu lugar no vídeo e pode continuar a assistir.
Estados de visibilidade de uma {{HTMLElement("iframe")}} são iguais ao documento original. Ocultar a iframe com propriedades CSS não desencadeia eventos de visibilidade nem altera o estado do documento de conteúdo.
The API is particularly useful for saving resources by giving developers the opportunity to not perform unnecessary tasks when the webpage is not visible.
Alguns exemplos:
Developers have historically used imperfect proxies to detect this. For example, registering an onblur/onfocus handler on the window helps you know when your page is not the active page, but it does not tell you that your page is hidden to the user. The Page Visibility API addresses this. (When compared with registering onblur/onfocus handlers on the window, a key difference is that a page does not become hidden when another window is made active and the browser window loses focus. A page only becomes hidden when the user switches to a different tab or minimizes the browser window.)
Along with the Page Visibility API, there are a number of policies in place to mitigate negative performance effects associated with background tabs:
Ver exemplo live (vídeo com som).
O exemplo, que pausa o vídeo quando muda para outro separador e reproduz novamente quando volta ao seu separador, foi criado com o seguinte código:
// Set the name of the hidden property and the change event for visibility var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 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 videoElement = document.getElementById("videoElement"); // If the page is hidden, pause the video; // if the page is shown, play the video function handleVisibilityChange() { if (document[hidden]) { videoElement.pause(); } else { videoElement.play(); } } // Warn if the browser doesn't support addEventListener or the 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 { // Handle page visibility change document.addEventListener(visibilityChange, handleVisibilityChange, false); // When the video pauses, set the title. // This shows the paused videoElement.addEventListener("pause", function(){ document.title = 'Paused'; }, false); // When the video plays, set the title. videoElement.addEventListener("play", function(){ document.title = 'Playing'; }, false); }
Returns true
if the page is in a state considered to be hidden to the user, and false
otherwise.
{{domxref("document.visibilityState")}} Read only
Is a string
denoting the visibility state of the document. Possible values:
visible
: the page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.hidden
: the page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active.prerender
: the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden
). The document may start in this state, but will never transition to it from another value. Note: browser support is optional.unloaded
: the page is being unloaded from memory. Note: browser support is optional.//startSimulation and pauseSimulation defined elsewhere function handleVisibilityChange() { if (document.hidden) { pauseSimulation(); } else { startSimulation(); } } document.addEventListener("visibilitychange", handleVisibilityChange, false);
{{domxref("document.onvisibilitychange")}}
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.
Especificação | Estado | Comentário |
---|---|---|
{{SpecName('Page Visibility API')}} | {{Spec2('Page Visibility API')}} | Initial definition. |
Funcionalidade | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Suporte básico | 13 {{property_prefix("webkit")}} 33 |
{{CompatGeckoDesktop(18)}}[2] | 10 | 12.10[1] | 7 |
onvisibilitychange |
{{CompatVersionUnknown}} | {{CompatGeckoDesktop(56)}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Budget-based background timeout throttling | 57 | {{CompatGeckoDesktop(58)}} | {{CompatNo}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Funcionalidade | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Suporte básico | 5.0[3] | {{CompatGeckoMobile(18)}}[2] | 10 | 12.10[1] | 7[4] |
onvisibilitychange |
{{CompatVersionUnknown}} | {{CompatGeckoMobile(56)}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Budget-based background timeout throttling | {{CompatNo}} | {{CompatGeckoMobile(58)}} | {{CompatNo}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
[1] Doesn't fire the {{event("visibilitychange")}} event when the browser window is minimized, nor set hidden
to true
.
[2] From Firefox 10 to Firefox 51 included, this property could be used prefixed with moz
.
[3] Android 4.4 supports this feature if prefixed with webkit
.
[4] From iOS 11.0.2 onwards, the values are not correct in standalone mode (when you press "Add to Homescreen") and when the screen is locked (you pressed the power button). The value for hidden
is false
and visibilityState
is visible
.