From c058fa0fb22dc40ef0225b21a97578cddd0aaffa Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:51:05 +0100 Subject: unslug ru: move --- files/ru/web/api/page_visibility_api/index.html | 195 ++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 files/ru/web/api/page_visibility_api/index.html (limited to 'files/ru/web/api/page_visibility_api') diff --git a/files/ru/web/api/page_visibility_api/index.html b/files/ru/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..9b181e92d1 --- /dev/null +++ b/files/ru/web/api/page_visibility_api/index.html @@ -0,0 +1,195 @@ +--- +title: Видимость страницы API +slug: Web/API/Видимость_страницы_API +tags: + - API + - DOM + - Документ + - Показать страницу + - Скрыть страницу +translation_of: Web/API/Page_Visibility_API +--- +
{{DefaultAPISidebar("Page Visibility API")}}
+ +

При переключении между вкладками, web страница переходит в фоновый режим и поэтому не видна пользователю. Page Visibility API предоставляет события, которые вы можете отслеживать, чтобы узнать, когда страница станет видимой или скрытой, а так же возможность наблюдать текущее состояние видимости страницы.

+ +
+

Notes: The Page Visibility API особенно полезно для сбережения ресурсов и улучшения производительности, позволяя странице остановить выполнение не нужных задач, когда она не видна.

+
+ +

Когда пользователь сворачивает окно или переключается на другую вкладку, API отправляет {{event("visibilitychange")}} событие обработчикам, что состояние страницы изменилось. Вы можете отследить это событие и выполнить какие-то действия. Например, если ваше app проигрывает видео, его можно поставить на паузу, когда пользователь переключил вкладку (страница ушла в фон), а затем возобновить видео, когда пользователь вернулся на вкладку. Пользователь не теряет место на котором остановил просмотр, звук от видео не конфликтует с аудио новой вкладки, пользователь комфортно просмотрить оба видео.

+ +

Состояния видимости для {{HTMLElement("iframe")}} такие же как и для родительской страницы. Скрытие <iframe> используя CSS стили (такие как {{cssxref("display", "display: none;")}}) не вызывают события видимости и не изменяют состояние документа, содержащегося во фрейме.

+ +

Использование

+ +

Давайте рассмотрим несколько способов использования Page Visibility API.

+ + + +

Раньше у разработчиков были не удобные способы. Например, обработка {{event("blur")}} и {{event("focus")}} событий на объекте window - помогала узнать когда страница становилась не активной, но это не давало возможность понять когда страница действительно скрыта от пользователя. Page Visibility API решает эту проблему.

+ +
+

Note: Когда {{domxref("GlobalEventHandlers.onblur", "onblur")}} и {{domxref("GlobalEventHandlers.onfocus", "onfocus")}} уведомляют, что пользователь переключил окна, это не означает, что оно действительно скрыто. Страница действительно скрыта, когда пользователь переключил вкладки или свернул окно браузера с этой вкладкой.

+
+ +

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:

+ + + +

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.

+ + + +

Example

+ +

View live example (video with sound).

+ +

The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:

+ +
// 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" || 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);
+
+}
+
+ +

Properties added to the Document interface

+ +

The Page Visibility API adds the following properties to the {{domxref("Document")}} interface:

+ +
+
{{domxref("Document.hidden")}} {{ReadOnlyInline}}
+
Returns true if the page is in a state considered to be hidden to the user, and false otherwise.
+
{{domxref("Document.visibilityState")}} {{ReadOnlyInline}}
+
A {{domxref("DOMString")}} indicating the document's current visibility state. Possible values are: +
+
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'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.
+
prerender
+
The page's content is being prerendered and is not visible to the user. A document may start in the prerender state, but will never switch to this state from any other state, since a document can only prerender once. +
Note: Not all browsers support prerendering.
+
+
unloaded
+
The page is in the process of being unloaded from memory. +
Note: Not all browsers support the unloaded value.
+
+
+
+
{{domxref("Document.onvisibilitychange")}}
+
An {{domxref("EventListener")}} providing the code to be called when the {{event("visibilitychange")}} event is fired.
+
+ +
//startSimulation and pauseSimulation defined elsewhere
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

Browser compatibility

+ +
+

Document.visibilityState

+ +
+ + +

{{Compat("api.Document.visibilityState")}}

+
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf