@bigfishtv/cockpit
Version:
43 lines (37 loc) • 1.03 kB
JavaScript
/**
* Window Visible Utility
* @module Utilities/windowVisible
*/
let stateKey = null
let eventKey = null
const keys = {
hidden: 'visibilitychange',
webkitHidden: 'webkitvisibilitychange',
mozHidden: 'mozvisibilitychange',
msHidden: 'msvisibilitychange',
}
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey]
break
}
}
/**
* Returns true/false if window is visible
* @param {Object} _window - defaults to window
* @return {Boolean}
*/
export function windowVisible(_window = window) {
return !_window.document[stateKey]
}
/**
* Adds 'visibilitychange' listener to window and binds to provided callback
* @param {Function} callback
* @param {Object} _window - defaults to window
* @return {Function}
*/
export function onVisibilityChange(callback, _window = window) {
const func = () => callback(windowVisible(_window))
_window.document.addEventListener(eventKey, func)
return () => _window && _window.document && _window.document.removeEventListener(eventKey, func)
}