(PHP) How to detect that user's computer/browser is in Dark Mode?

后端 未结 2 1439
闹比i
闹比i 2021-01-13 03:06

Lately I am updating my software to support dark mode, in response to research that looking at a paper-white background display is bad for the eyes and for sleep rhythms. Is

2条回答
  •  轮回少年
    2021-01-13 03:41

    Unfortunately the dark mode detection methodology does not exist for server side-processing (including PHP).

    • All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack, and the Media Queries Level 5 specification uses a prefers-color-scheme media query for detection. This useful in both CSS and JavaScript.

    • There is a recommendation by Thomas Steiner (@DenverCoder9) from Google to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.

    • Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.

    • The recommendation is to leave this detection on the client and projects like vinorodrigues/bootstrap-dark show how easy that can be - without server-side processing.

    Having said that - there is a workaround:

    The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:

      
      
    

    And then your PHP will detect this cookie like this:

      $color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
      if ($color_scheme === false) $color_scheme = 'light';  // fallback
    

    Which you can use to load the CSS:

      // Load the CSS for the correct color-scheme
      if ($color_scheme == 'dark') {
        ?>

    Or, like this:

      ?>You are in  mode.

提交回复
热议问题