Zhihu Auto Theme Sync

Automatically toggle Zhihu's light/dark mode based on system color scheme.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램을 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Zhihu Auto Theme Sync
// @name:zh-CN   知乎自动跟随系统主题
// @namespace    https://github.com/Linsama/toolbox
// @version      1.0.0
// @description  Automatically toggle Zhihu's light/dark mode based on system color scheme.
// @description:zh-CN 自动根据系统偏好(深色/浅色模式)切换知乎网页版主题。
// @author       Linsama
// @match        *://*.zhihu.com/*
// @grant        none
// @run-at       document-start
// @license      MIT
// @icon         https://www.google.com/s2/favicons?sz=64&domain=zhihu.com
// @supportURL   https://github.com/Linsama/toolbox/issues
// ==/UserScript==

(function() {
    'use strict';

    /**
     * Staff Engineer Note:
     * We use document-start to minimize FOUC (Flash of Unstyled Content).
     * The redirection is handled via URL parameters which Zhihu uses to set its theme cookies.
     */
    function syncTheme() {
        const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        const targetTheme = isSystemDark ? 'dark' : 'light';

        const url = new URL(window.location.href);
        const currentThemeParam = url.searchParams.get('theme');

        // Prevent infinite redirect loops
        if (currentThemeParam === targetTheme) return;

        // Double check the actual rendered theme to avoid unnecessary reloads
        const currentActualTheme = document.documentElement.getAttribute('data-theme');
        if (currentActualTheme === targetTheme) return;

        // Apply theme via URL parameter
        url.searchParams.set('theme', targetTheme);

        // Use replace() to keep browser history clean
        window.location.replace(url.toString());
    }

    // Initial check
    syncTheme();

    // Listen for system theme changes in real-time
    const matcher = window.matchMedia('(prefers-color-scheme: dark)');
    try {
        matcher.addEventListener('change', syncTheme);
    } catch (e) {
        // Fallback for older browser engines
        matcher.addListener(syncTheme);
    }
})();