使用JavaScript阻止屏幕进入睡眠状态

**Implementing Screen Brightness Persistence via JavaScript** **Screen Brightness Control via Native APIs** In H5 development scenarios, to meet the requirement of continuous display, the use of native browser APIs for screen wake-up control is required. This technology is supported in Chrome 85, though Safari has not yet implemented it. However, it can be directly called on Android devices, and the iOS implementation can adopt a polyfill approach, which will be removed once Safari supports it. **Wake Lock API** The Wake Lock API prevents screen shutdown, dimming, or locking, and is limited to active browser windows. It effectively avoids resource consumption by background processes. **Compatibility Check** Before implementation, verify browser compatibility using the following function: ```javascript const canWakeLock = () => 'wakeLock' in navigator; ``` **Acquiring a Wake Lock** The following example demonstrates how to obtain a Wake Lock object: ```javascript let wakeLock = null; ``` **Asynchronous Wake Lock Acquisition** Implementing the Wake Lock request using `async/await` syntax: ```javascript let wakeLock = null; ``` **Releasing a Wake Lock** Calling `wakeLock.release()` releases the acquired wake lock, and the variable must be reset afterward: ```javascript wakeLock.release().then(() => wakeLock = null); ``` **Listening for Wake Lock Release Events** When the wake lock is released due to page closure or other reasons, the `release` event is triggered: ```javascript wakeLock.addEventListener('release', () => { console.log('Wake Lock has been released'); }); ``` **Dynamic Wake Lock Acquisition** Trigger the re-acquisition of a wake lock based on document visibility changes: ```javascript document.addEventListener('visibilitychange', async () => { if (wakeLock !== null && document.visibilityState === 'visible') { requestWakeLock(); } }); ``` **Final Notes** - The `wakeLock` variable is initialized as `null` in all examples. - The `requestWakeLock()` function is assumed to be implemented elsewhere. - The polyfill approach for iOS is recommended for future compatibility.