requestFullscreen Resolves Or Rejects By State
Await requestFullscreen with options, handle its rejection paths, and follow fullscreenchange plus exitFullscreen to track element state.
Code
// The promise-based fullscreen API: requestFullscreen resolves when
// the element actually enters fullscreen, and rejects when the user
// gesture or document state forbids it
const stage = document.querySelector<HTMLElement>('#stage');
async function enterStage(): Promise<void> {
try {
await stage?.requestFullscreen({ navigationUI: 'hide' });
console.log(`fullscreen: ${document.fullscreenElement === stage}`);
} catch {
// DOMException names carry the reason: TypeError, NotAllowedError...
console.log('fullscreen denied');
}
}
async function leaveStage(): Promise<void> {
if (document.fullscreenElement) {
await document.exitFullscreen();
console.log(`fullscreen: ${document.fullscreenElement === null}`);
}
}
document.addEventListener('fullscreenchange', () => {
console.log(`state change: ${Boolean(document.fullscreenElement)}`);
});The promise that resolves or rejects
stage?.requestFullscreen({ navigationUI: 'hide' }) resolves when the element actually enters fullscreen and rejects when the user gesture or document state forbids it. Inside enterStage, success logs `fullscreen: ${document.fullscreenElement === stage}` — the equality check against fullscreenElement is how the code verifies the element, not just “some” element, went fullscreen — and the catch logs fullscreen denied for the DOMException paths (the comment names TypeError, NotAllowedError).
Tracking the state changes
leaveStage guards on document.fullscreenElement before calling await document.exitFullscreen(), then logs `fullscreen: ${document.fullscreenElement === null}`. Independently of either function, the fullscreenchange listener logs `state change: ${Boolean(document.fullscreenElement)}` on every transition, so the console records both directions whatever triggered them.
The line that follows the transition
document.addEventListener('fullscreenchange', () => {
console.log(`state change: ${Boolean(document.fullscreenElement)}`);
});
The fullscreen APIs used here live in the browser (document does not resolve under plain Node), so execute it inside a browser page; which of the two logs appears first depends on the gesture and the browser’s policy, not on source order.
Interactive Tools for This Topic
FAQ
- Does requestFullscreen Resolves Or Rejects By State run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.