推特 X.com 自动主题切换

根据系统主题自动切换 X.com (原 Twitter) 的主题,代码使用Devv.AI协助编写。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         推特 X.com 自动主题切换
// @version      1.1
// @description  根据系统主题自动切换 X.com (原 Twitter) 的主题,代码使用Devv.AI协助编写。
// @author       Devv.AI
// @match        https://x.com/*
// @icon         https://x.com/favicon.ico
// @namespace    hengyuan
// @license      MIT
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function applyTheme(theme) {
        document.cookie = `night_mode=${theme}; domain=.x.com; path=/; secure; max-age=31536000`;
        // 立即应用主题更改,避免刷新页面前出现闪烁
        document.documentElement.setAttribute('data-night-mode', theme);
        // 触发 X.com 内部的主题更新机制 (如果存在)
        window.dispatchEvent(new Event('nightModeUpdated'));
    }

    function detectSystemTheme() {
        const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
        return darkModeQuery.matches ? '2' : '0'; // 2: 暗黑, 0: 默认
    }

    function updateTheme() {
        const systemTheme = detectSystemTheme();
        applyTheme(systemTheme);
    }

    // 初始应用主题
    updateTheme();

    // 监听系统主题变化
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
    darkModeQuery.addEventListener('change', updateTheme);


    // 处理 X.com 异步加载内容的情况
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type === 'childList' && mutation.addedNodes.length) {
                updateTheme(); // 页面内容变化时重新应用主题
            }
        });
    });

    observer.observe(document.body, { childList: true, subtree: true });

})();