Html event on visible

Document: visibilitychange event

The visibilitychange event is fired at the document when the contents of its tab have become visible or have been hidden.

The event is not cancelable.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("visibilitychange", (event) => >); onvisibilitychange = (event) => >; 

Event type

Usage notes

The event doesn’t include the document’s updated visibility status, but you can get that information from the document’s visibilityState property.

This event fires with a visibilityState of hidden when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app. Transitioning to hidden is the last event that’s reliably observable by the page, so developers should treat it as the likely end of the user’s session (for example, for sending analytics data).

The transition to hidden is also a good point at which pages can stop making UI updates and stop any tasks that the user doesn’t want to have running in the background.

Examples

Pausing music on transitioning to hidden

This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible.

.addEventListener("visibilitychange", () =>  if (document.visibilityState === "visible")  backgroundMusic.play(); > else  backgroundMusic.pause(); > >); 

Sending end-of-session analytics on transitioning to hidden

This example treats the transition to hidden as the end of the user’s session, and sends the appropriate analytics using the Navigator.sendBeacon() API:

.onvisibilitychange = () =>  if (document.visibilityState === "hidden")  navigator.sendBeacon("/log", analyticsData); > >; 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Page Visibility API
  • Document.visibilityState
  • Don’t lose user and app state, use Page Visibility explains in detail why you should use visibilitychange , not beforeunload / unload .
  • Page Lifecycle API gives best-practices guidance on handling page lifecycle behavior in your web applications.

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Page Visibility API

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn’t visible.

Concepts and usage

When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn’t lose their place in the video, the video’s soundtrack doesn’t interfere with audio in the new foreground tab, and the user doesn’t miss any of the video in the meantime.

Visibility states of an are the same as the parent document. Hiding an using CSS properties (such as display: none; ) doesn’t trigger visibility events or change the state of the document contained within the frame.

Use cases

Let’s consider a few use cases for the Page Visibility API.

  • A site has an image carousel that shouldn’t advance to the next slide unless the user is viewing the page
  • An application showing a dashboard of information doesn’t want to poll the server for updates when the page isn’t visible
  • A page wants to detect when it is being prerendered so it can keep accurate count of page views
  • A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)

Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.

Note: While onblur and onfocus will tell you if the user switches windows, it doesn’t necessarily mean it’s hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.

Policies in place to aid background page performance

Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:

  • Most browsers stop sending requestAnimationFrame() callbacks to background tabs or hidden s in order to improve performance and battery life.
  • Timers such as setTimeout() are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details.
  • Browsers implement budget-based background timeout throttling. This operates in a similar way across modern browsers, with the details being as follows:
    • In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
    • Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see Reasons for delays longer than specified). In Chrome, this value is 10 seconds.
    • Timer tasks are only permitted when the budget is non-negative.
    • Once a timer’s code has finished running, the duration of time it took to execute is subtracted from its window’s timeout budget.
    • The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.

    Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs’ performance impact while they’re hidden.

    • Tabs which are playing audio are considered foreground and aren’t throttled.
    • Tabs running code that’s using real-time network connections (WebSockets and WebRTC) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
    • IndexedDB processes are also left unthrottled in order to avoid timeouts.

    Extensions to other interfaces

    Instance properties

    The Page Visibility API adds the following properties to the Document interface:

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

    A string indicating the document’s current visibility state. Possible values are:

    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.

    The page’s content is not visible to the user, either due to the document’s tab being in the background or part of a window that is minimized, or because the device’s screen is off.

    Events

    The Page Visibility API adds the following events to the Document interface:

    Fired when the content of a tab has become visible or has been hidden.

    Examples

    Pausing audio on page hide

    This example pauses audio when the user switches to a different tab, and plays when they switch back.

    HTML

    audio controls src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3">audio> 

    JavaScript

    const audio = document.querySelector("audio"); // Handle page visibility change: // - If the page is hidden, pause the video // - If the page is shown, play the video document.addEventListener("visibilitychange", () =>  if (document.hidden)  audio.pause(); > else  audio.play(); > >); 

    Result

    Try playing the audio, then switching to a different tab and back again.

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    Found a content problem with this page?

    This page was last modified on Feb 19, 2023 by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    Our communities

    Developers

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Источник

    Page Visibility API: Know when a user is on your page

    Learn Algorithms and become a National Programmer

    There was a need for the developers to know when a user is leaving the page. There are three events that can help us achieve this task. They are:

    However, these events may not be triggered on the phone and the page is closed directly, as the mobile system can transfer a process into the background directly and then kill it.

    The situations that pages were switched by the system and the system cleared the browser process, couldn’t be monitored. And it was impossible for developers to specify the code that can be executed under any case of unloading a page. In order to solve this problem, Page Visibility API was introduced. The API will listen to any visible change of the page under all the cases, regardless of that, it’s on the the phone or desktop.

    The Page Visibility API can be used to predict the unloading of the web page. Also, it can save resources by slowing down the consumption of power.

    For Example, it can be used to pause a video playback, when the user is not looking at the page.

    1. The document.visibilityState property

    This API mainly adds a document.visibilityState property to the document object. The property returns a string representing the current visibility state of the page, with a total of three possible values:

    • hidden:The page is completely invisible.
    • visible:The page is visible.
    • prerender:The page is about to be or is being rendered and it is invisible.

    The hidden and visible states are supported by all browsers. The prerender state only appears on browsers that support «pre-rendering». For example, the Chrome browser has a pre-rendering function which can render the page in advance under the invisible state to users, and display the rendered we bpage directly when the user wants to browse the page.

    The document.visibilityState property returns visible, even if only a part of a web page is visible to the user. The value of document.visibilityState returns hidden only if,

    • The browser is minimized.
    • Though the browser is not minimized, the current page is switched to be a background page.
    • The browser will unload the page.
    • The operating system triggers the lock screen.

    Important: In addition, in the earlier version of the API, there is a fourth value unloaded which is used to indicate that the page is about to be unloaded, which is now deprecated.

    2. The document.hidden property

    This property returns a boolean value, which indicates that the current page is visible or not.
    The document.hidden property returns false when the document.visibilityState property returns visible. In other cases, it returns true.

    Important: The property is reserved for historical reasons only, and whenever possible, you should use the document.visibilityState property instead.

    3. The visibilitychange event

    The visibilitychange event will be triggered as long as the document.visibilityState property changes. Thus, we can track changes on page visibility by listening to this event through document.addEventListener() method or the document.onvisibilitychange property. The below example shows the basic usage of this event.

    document.addEventListener('visibilitychange', function () < // The user leaves the current page. if (document.visibilityState === 'hidden') < alert('Page is not visible'); >// The user opens or returns to the page. if (document.visibilityState === 'visible') < alert('Page is visible'); >>); 

    It can be also used to automatically pause a video when the user is not viewing the web page. The code snippet below shows an example of this feature.

    var vidElement = document.getElementById('video-demo'); document.addEventListener('visibilitychange', startStopVideo); function startStopVideo() < if (document.visibilityState === 'hidden') < vidElement.pause(); >else if (document.visibilityState === 'visible') < vidElement.play(); >> 

    Output of Example 2:

    The Video will Stop playing when you switch to other tab or minimize the browser. Your browser does not support the video tag.

    4. Page Unloading

    There can be three situations about unloading a page. Firstly, the page is visible, the user closes the Tab page or the browser window. Secondly, the page is visible, the user goes to another page from the current window. Lastly, the page is not visible, the user or system closes the browser window. All of the three cases will trigger the visibilitychange event. Under the first two cases, the event is triggered when the user leaves the page. And, under the last case, the event is triggered when the page changes from the visible state to the invisible state.

    Источник

    Читайте также:  Count number characters python
Оцените статью