background-color

Change the white elements to green for protecting your eyes!

目前为 2018-10-13 提交的版本。查看 最新版本

// ==UserScript==
// @name         background-color
// @namespace    http://tampermonkey.net/
// @version      0.7.0
// @description  Change the white elements to green for protecting your eyes!
// @author       developerdong
// @match        http*://*/*
// @grant        none
// ==/UserScript==
(function () {
    'use strict';

    function toHex(N) {
        if (N == null) return "00";
        N = parseInt(N);
        if (N === 0 || isNaN(N)) return "00";
        N = Math.max(0, N);
        N = Math.min(N, 255);
        N = Math.round(N);
        // return "0123456789abcdef".charAt((N - N % 16) / 16) + "0123456789abcdef".charAt(N % 16); // Lower case
        return "0123456789ABCDEF".charAt((N - N % 16) / 16) + "0123456789ABCDEF".charAt(N % 16); // Upper case
    }

    /**
     * Transform RGB color to HEX color
     * @return {string}
     */
    function RGBtoHEX(str) {
        if (str.substring(0, 3) === 'rgb') {
            const arr = str.split(",");
            const r = arr[0].replace('rgb(', '').trim(),
                  g = arr[1].trim(),
                  b = arr[2].replace(')', '').trim();
            const hex = [toHex(r), toHex(g), toHex(b)];
            return "#" + hex.join('');
        } else {
            return str;
        }
    }

    /**
     * Change the background color of all sub elements by level order
     */
    function changeBackgroundColor(node) {
        const queue = [];
        while (node) {
            // nodeType == 1 means the node is an element
            if (node.nodeType === 1) {
                const nodeStyle = window.getComputedStyle(node);
                if (RGBtoHEX(nodeStyle.backgroundColor) === "#FFFFFF" && nodeStyle.cursor === "auto") {
                    node.style.setProperty("background-color", "#C1E6C6", "important");
                }
                Array.from(node.children).forEach(function (child) {
                    queue.push(child);
                });
            }
            node = queue.shift();
        }
    }

    // Change the background color of newly added elements
    const observer = new MutationObserver(function (records){
        records.map(function(record){
            if (record.type === "childList") {
                record.addedNodes.forEach(changeBackgroundColor);
            }
        });
    });
    const option = {
        'childList': true,
        'subtree': true
    };
    observer.observe(document.body, option);
    
    // Change the background color of initially loaded elements
    changeBackgroundColor(document.body);

})();