实现说明
requestFullscreen 的兑现与拒绝以函数 enterStage、leaveStage为骨架。
await 标出每个异步边界——没有 fire-and-forget。
使用要点
- 这是浏览器侧代码——
document在 Node 里解析不到。 - 跑完文件,输出里会留下标记——
fullscreen: $、fullscreen denied、state change: $。
常见问题
「requestFullscreen 的兑现与拒绝」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。
入口签名:async function enterStage()
核心语句
await stage?.requestFullscreen({ navigationUI: 'hide' });
document.addEventListener('fullscreenchange', () => {
console.log(`state change: ${Boolean(document.fullscreenElement)}`);
});
async function leaveStage(): Promise<void> {
if (document.fullscreenElement) {
await document.exitFullscreen();
console.log(`fullscreen: ${document.fullscreenElement === null}`);
}
}
代码示例
// 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)}`);
});