focusManager is a singleton that manages window focus state and notifies subscribers when the focus state changes. It listens to the visibilitychange event by default and can be customized with custom event listeners.
Import
Methods
subscribe
Subscribe to focus state changes.Callback function that will be called when the focus state changes. Receives a boolean indicating whether the window is focused.
Returns an unsubscribe function that removes the listener when called.
Example
setEventListener
Set a custom event listener for focus changes. This allows you to customize how focus is detected.A setup function that receives a
setFocused callback and returns an optional cleanup function.Type signature:The setup function should call
setFocused(true) when the window gains focus and setFocused(false) when it loses focus. If called with no arguments, it will use the default focus detection.Example
setFocused
Manually set the focus state.The new focus state. If not provided, the focus state will be determined automatically using the default detection method.
Example
isFocused
Get the current focus state.Returns
true if the window is focused, false otherwise. If no manual focus state has been set, it checks document.visibilityState !== 'hidden'.Example
Default Behavior
By default, thefocusManager listens to the browser’s visibilitychange event to detect when the window gains or loses focus. This works in most browser environments.
In environments where window.addEventListener is not available (like React Native), you need to set up a custom event listener using setEventListener.