JS monitors the display and hiding of browser tabs
API
-
document.hidden
is a Boolean value that determines whether the page is hidden. Page hiding includes pages in background tabs or minimized browsers -
document.visibilityState
(read-only property), returns the visibility of the document, 4 values:
hidden: the document is in a background tab or the window is minimized, or the operating system is in the 'lock screen state'visible: This page is in the foreground tab and the window is not minimized
prerender: The page performs pre-rendering off the screen. The value of document.hidden is true.
unloaded: The page is being unloaded from memory
-
visibilitychange event
This event is triggered when a tab changes from visible to invisible or from invisible to visible (including tab switching and browser minimization).
document.addEventListener('visibilitychange', function() {
var isHidden = document.hidden;
console.log(document.visibilityState)
if (isHidden) {
document.title = '隐藏';
} else {
document.title = '显示';
}
});
Browser compatibility
Chrome (Webkit) Firefox (Gecko) Internet Explorer
33+(-webkit-) 56+(-moz-) 10+(-ms-)
Applicable scene
Stop playing music videos and unnecessary polling when the tab is hidden