isFullscreen
Checks if the document is currently in fullscreen mode.
1/**
2 * Checks if the document is currently in fullscreen mode.
3 *
4 * @returns True if fullscreen is active, false otherwise.
5 */
6export function isFullscreen(): boolean {
7 if (typeof document === 'undefined') return false;
8
9 return !!(
10 document.fullscreenElement ||
11 (document as any).webkitFullscreenElement ||
12 (document as any).mozFullScreenElement ||
13 (document as any).msFullscreenElement
14 );
15}
Cross-Browser Compatibility
Supports multiple vendor-prefixed properties (
webkit
,moz
,ms
) to handle fullscreen detection across different browsers.Environment Safety
Includes a guard clause for non-browser environments to avoid runtime errors.
Boolean Normalization
Always returns a strict boolean using double negation (
!!
), ensuring predictable results.Minimal Overhead
Performs a lightweight property check without triggering layout or reflow, making it very efficient.
Tests | Examples
1test('isFullscreen - returns true if document.fullscreenElement exists', () => {
2 const original = document.fullscreenElement;
3 Object.defineProperty(document, 'fullscreenElement', {
4 configurable: true,
5 value: {},
6 });
7
8 expect(isFullscreen()).toBe(true);
9
10 Object.defineProperty(document, 'fullscreenElement', {
11 configurable: true,
12 value: original,
13 });
14});
15
16test('isFullscreen - returns false if no fullscreen properties are set', () => {
17 const original = document.fullscreenElement;
18 Object.defineProperty(document, 'fullscreenElement', {
19 configurable: true,
20 value: null,
21 });
22
23 expect(isFullscreen()).toBe(false);
24
25 Object.defineProperty(document, 'fullscreenElement', {
26 configurable: true,
27 value: original,
28 });
29});
Common Use Cases
UI Toggle Indicators
Display fullscreen icons or messages based on the current state.
Keyboard Shortcut Handlers
Determine whether to enter or exit fullscreen when specific keys are pressed.
Media Playback Enhancements
Adapt UI or controls based on whether a video or game is in fullscreen.
Prevent Redundant Requests
Avoid calling
requestFullscreen()
if the document is already in fullscreen mode.