# Screen Wake Lock API

The Screen Wake Lock API provides a way to prevent devices from dimming or locking the screen when an application needs to keep running. This is essential for use cases like recipe apps, presentation tools, or QR code tickets where the user might not interact with the screen for a while but needs it to stay on.

## 1. Requesting a Wake Lock

To request a wake lock, you use the `navigator.wakeLock.request()` method. It returns a Promise that resolves to a `WakeLockSentinel` object.

```javascript
let wakeLock = null;

async function requestWakeLock() {
  try {
    wakeLock = await navigator.wakeLock.request('screen');
    console.log('Wake Lock is active!');
    
    wakeLock.addEventListener('release', () => {
      console.log('Wake Lock was released');
    });
  } catch (err) {
    console.error(`${err.name}, ${err.message}`);
  }
}

requestWakeLock();
```

## 2. Releasing the Lock

You can manually release the lock using the `release()` method on the sentinel object.

```javascript
function releaseWakeLock() {
  if (wakeLock !== null) {
    wakeLock.release();
    wakeLock = null;
  }
}
```

## 3. Automatic Release and Re-acquisition

The browser automatically releases the wake lock when the page loses visibility (e.g., user switches tabs or minimizes the window).

To ensure the screen stays on when the user returns to your tab, you must listen for the `visibilitychange` event and re-request the lock.

```javascript
document.addEventListener('visibilitychange', async () => {
  if (wakeLock !== null && document.visibilityState === 'visible') {
    await requestWakeLock();
  }
});
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/page-visibility-api]]
[[programming/javascript/vanilla/promises-async-await]]