enterFullscreen
Requests fullscreen mode for a given element.
1/**
2 * Requests fullscreen mode for a given element.
3 *
4 * @param element - The DOM element to enter fullscreen. Defaults to document.documentElement.
5 */
6export function enterFullscreen(element: HTMLElement = document.documentElement): void {
7 const request = element.requestFullscreen
8 || (element as any).webkitRequestFullscreen
9 || (element as any).mozRequestFullScreen
10 || (element as any).msRequestFullscreen;
11
12 if (request) {
13 request.call(element);
14 } else {
15 console.warn('Fullscreen API is not supported by this browser.');
16 }
17}
Cross-Browser Compatibility
Supports multiple vendor-prefixed versions (
webkit
,moz
,ms
) of the Fullscreen API, ensuring broader browser support.Graceful Fallback
Provides a fallback warning if fullscreen is not supported, helping developers detect unsupported environments.
Default Target Support
Defaults to
document.documentElement
, which covers the common case of making the whole page fullscreen.Minimal Interface
Simple and intuitive signature with a single optional parameter, making it easy to integrate.
Tests | Examples
1test('enterFullscreen calls requestFullscreen if available', () => {
2 const mockRequest = vi.fn();
3 const element = {
4 requestFullscreen: mockRequest
5 } as unknown as HTMLElement;
6
7 enterFullscreen(element);
8 expect(mockRequest).toHaveBeenCalled();
9});
10
11test('enterFullscreen falls back to vendor-prefixed methods', () => {
12 const mockWebkit = vi.fn();
13 const element = {
14 webkitRequestFullscreen: mockWebkit
15 } as unknown as HTMLElement;
16
17 enterFullscreen(element);
18 expect(mockWebkit).toHaveBeenCalled();
19});
20
21test('enterFullscreen warns if fullscreen is not supported', () => {
22 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
23 const element = {} as HTMLElement;
24
25 enterFullscreen(element);
26 expect(warnSpy).toHaveBeenCalledWith('Fullscreen API is not supported by this browser.');
27
28 warnSpy.mockRestore();
29});
Common Use Cases
Video Players
Enable fullscreen mode for custom video containers or media players.
Image/Gallery Viewers
Allow users to view images or slideshows in fullscreen for a better experience.
Presentations or Slides
Trigger fullscreen for decks or slide components in web-based presentation tools.
Interactive Applications
Enhance focus and immersion for games, simulations, or drawing apps.
Accessibility or Focus Mode
Provide distraction-free viewing for reading or writing environments.