Unicode 自动翻译脚本

实时翻译网页上的 Unicode 编码为中文

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Unicode 自动翻译脚本
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  实时翻译网页上的 Unicode 编码为中文
// @author       barnett2010
// @match        *://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 翻译单个节点的文本
    function translateNode(node) {
        if (node.nodeType === 3) {
            var text = node.nodeValue;
            var decodedText = text.replace(/\\u([\dA-F]{4})/gi, function(match, p1) {
                return String.fromCharCode(parseInt(p1, 16));
            });
            if (decodedText !== text) {
                node.nodeValue = decodedText;
            }
        }
    }

    // 遍历页面上的节点,并翻译文本
    function translateUnicode() {
        var elements = document.getElementsByTagName('*');
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            for (var j = 0; j < element.childNodes.length; j++) {
                var node = element.childNodes[j];
                translateNode(node);
            }
        }
    }

    // 监听页面变化,实时翻译
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.nodeType === 3) {
                    translateNode(node);
                } else if (node.getElementsByTagName) {
                    var elements = node.getElementsByTagName('*');
                    for (var j = 0; j < elements.length; j++) {
                        var subNode = elements[j];
                        translateNode(subNode);
                    }
                }
            }
        });
    });

    // 开始监听页面变化
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // 在页面加载完成后立即翻译
    window.addEventListener('load', function() {
        translateUnicode();
    });

})();