Zhihu Auto Dark Mode

Automatically toggle hidden built-in dark mode on zhihu.com

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Zhihu Auto Dark Mode
// @namespace    http://tampermonkey.net/
// @version      0.4
// @description  Automatically toggle hidden built-in dark mode on zhihu.com
// @author       Nathaniel Wu
// @include      *.zhihu.com/*
// @exclude      *link.zhihu.com/*
// @exclude      *www.zhihu.com/question/*/log
// @exclude      *www.zhihu.com/people/*/logs
// @license      Apache-2.0
// @supportURL   https://gist.github.com/Nathaniel-Wu/b2e6490f5ac7c35dc0cd902fda851b36
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    const setDarkMode = on => {
        let alreadyOn = document.querySelector('html').getAttribute('data-theme') == 'dark';
        if ((alreadyOn && (!on)) || ((!alreadyOn) && on)) {
            let keyword, keyword_replacement;
            if (on) {
                keyword = 'theme=light';
                keyword_replacement = 'theme=dark';
            } else {
                keyword = 'theme=dark';
                keyword_replacement = 'theme=light';
            }
            if (window.location.href.match(/theme=(dark|light)/))
                window.location.href = window.location.href.replace(keyword, keyword_replacement);
            else {
                if (window.location.href.match(/\?[^=]+=/))
                    window.location.href = window.location.href + `&${keyword_replacement}`;
                else
                    window.location.href = window.location.href + `?${keyword_replacement}`;
            }
        }
    }
    const in_iframe = () => {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }
    if (!in_iframe()) {
        if (window.matchMedia) {// if the browser/os supports system-level color scheme
            setDarkMode(window.matchMedia('(prefers-color-scheme: dark)').matches);
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => setDarkMode(e.matches));
        } else {// otherwise use local time to decide
            let hour = (new Date()).getHours();
            setDarkMode(hour > 18 || hour < 8);
        }
    }
})();