知乎暗黑模式

自动运行知乎暗黑模式

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         知乎暗黑模式
// @namespace    undefined
// @version      0.1
// @description  自动运行知乎暗黑模式
// @author       fyang0728
// @match        *://*.zhihu.com/*
// @icon         none
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    console.log(123);
    document.querySelector('html').dataset.theme = 'dark';

    // 选择需要观察变动的节点
    var targetNode = document.querySelector('html');

    // 观察器的配置(需要观察什么变动)
    var config = { attributes: true, childList: false, subtree: false };

    // 当观察到变动时执行的回调函数
    var callback = function (mutationsList, observer) {

        console.log('-------------元素观察者开始运行-------------');

        for (var mutation in mutationsList) {
            if (mutationsList[mutation].type === 'attributes') {
                if (
                    document.querySelector('html').getAttribute('data-theme') !== 'dark'
                ) {
                    console.log('这个' + mutationsList[mutation].attributeName + '属性被修改...');
                    document.querySelector('html').dataset.theme = 'dark';
                }
            }
        }
    };

    // 创建一个观察器实例并传入回调函数
    var observer = new MutationObserver(callback);

    // 以上述配置开始观察目标节点
    observer.observe(targetNode, config);
})();