Fix <code> bug for Edge translator

把网页中的所有<code>标签替换成同样式<span>,以修复Edge内置翻译器bug

目前为 2024-02-17 提交的版本。查看 最新版本

// ==UserScript==
// @name         Fix <code> bug for Edge translator
// @name:zh-CN   Fix <code> bug for Edge translator
// @namespace    http://tampermonkey.net/
// @version      1.0.1
// @description  Replace <code> tags with styled <span> to fix the bug of Edge's translator.
// @description:zh-CN  把网页中的所有<code>标签替换成同样式<span>,以修复Edge内置翻译器bug
// @author       yqs112358
// @license      MIT
// @match        *://*/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // Replace a single <code> tag with a same-styled <span>
    function replaceCodeToSpan(node) {
        if (node.tagName === 'CODE') {
            const span = document.createElement('span');

            // Copy all attributes
            Array.from(node.attributes).forEach(attr => {
                span.setAttribute(attr.name, attr.value);
            });
            // Copy all computed styles
            const computedStyle = window.getComputedStyle(node);
            for (let key of computedStyle) {
                span.style[key] = computedStyle[key];
            }
            // Copy InnerHTML
            span.innerHTML = node.innerHTML;

            node.parentNode.replaceChild(span, node);
        }
    }

    // Process a node and its child for <code> tags
    function processNodeAndChild(node) {
        if (node.nodeType === 1) {      // Element node
            node.querySelectorAll('code').forEach(replaceCodeToSpan);
            replaceCodeToSpan(node);
        }
    }

    ////////////////////////////////////////////////////////

    // Replace <code> at startup
    document.querySelectorAll('code').forEach(replaceCodeToSpan);

    // Observe DOM changes and replace new-generated <code> if needed
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            mutation.addedNodes.forEach(processNodeAndChild);
        });
    });
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址