Bilibili - 自动同步系统主题并刷新

自动同步系统主题并刷新

// ==UserScript==
// @name         Bilibili - 自动同步系统主题并刷新
// @namespace    http://tampermonkey.net/
// @version      2025-08-08
// @description  自动同步系统主题并刷新
// @author       You
// @license      MIT
// @match        https://*.bilibili.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=bilibili.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const systemTheme = prefersDark ? 'dark' : 'light';

    const cookies = document.cookie.split('; ');
    const themeCookie = cookies.find(row => row.startsWith('theme_style='));
    const biliTheme = themeCookie ? themeCookie.split('=')[1] : null;

    function switchThemeAndReload(theme) {
        document.cookie = `theme_style=${theme}; path=/; max-age=31536000`;
        location.reload();
    }

    if (biliTheme !== systemTheme) {
        switchThemeAndReload(systemTheme);
    }

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    mediaQuery.addEventListener('change', (e) => {
        const newTheme = e.matches ? 'dark' : 'light';
        if (biliTheme !== newTheme) {
            switchThemeAndReload(newTheme);
        }
    });
    // Your code here...
})();