[w3c/ServiceWorker] Allow service workers to detect light/dark mode (#1577)

## Problem

Service workers should exposed a way to detect if the user prefers light mode, dark mode, and possibly that the use rhas not declared a preference. It's currently possible for a page's CSS to detect this using `@media (prefers-color-scheme: <VALUE>) {}` or in JavaScript using the below snippet. Unfortunately, this approach does not work inside a service worker as `matchMedia` is not exposed there. 

```js
let mqList = window.matchMedia('(prefers-color-scheme: dark)');
if (mqList.matches) {
  // handle dark mode
} else {
  // handle light mode
}
```

While it is possible for a page to postMessage this information to a service worker or write this setting somewhere accessible to the service worker, these approaches require coordination between disparate parts of a page.

## Proposal

Expose a new property on `ServiceWorkerGlobalScope` named `prefersColorScheme` that exposes a value as described in the prefers-color-scheme section of the CSS Media Queries specification ([Media Queries Level 5 working draft](https://www.w3.org/TR/mediaqueries-5/#prefers-color-scheme)). 

## Additional Context

My initial use case was inside a Chrome extension's service worker, but I suspect that this capability would be useful for standard service workers as well. For example, this information could be used to prepopulate the cache with image assets for the user's prefered color scheme. 

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1577

Received on Tuesday, 6 April 2021 21:30:43 UTC