I was recently asked if there were ways to programmatically determine if users had Windows high contrast mode, or dark color schemes enabled at the OS level.

The most straight forward way to do this is to use their media queries in CSS (forced-colors: active and prefers-color-scheme: dark, repsectively).

Yes, yes, sure, sure. But… What about with JavaScript?

Also, yes. You can do that too. And the following is a super quick way to test that.

const h = matchMedia('(forced-colors: active)');
const d = matchMedia('(prefers-color-scheme: dark)');

function checks() {
	if ( h.matches ) {
		console.log('high contrast enabled');
	}
	if ( d.matches ) {
		console.log('dark mode enabled');
	}
}
// run the checks immediately
checks();

// listen for any changes performed by people tinkering with their settings
h.addListener(checks);
d.addListener(checks);

Or futz with it in the CodePen

See the Pen JavaScript to detect media queries by Scott (@scottohara) on CodePen.

This is really just the same sort of checks I used in my Reduced Motion Auto-Play Video post, to setup some logic to enable/disable autoplaying of a video based on someone’s reduced motion settings.

Update: hey, you not getting the results you were expecting with this script? Go give Sara Soueidan’s “The CSS prefers-color-scheme user query and order of preference” post a read for more information.