Fix <code> bug for Edge translator

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

  1. // ==UserScript==
  2. // @name Fix <code> bug for Edge translator
  3. // @name:zh-CN Fix <code> bug for Edge translator
  4. // @namespace http://tampermonkey.net/
  5. // @version 1.0.2
  6. // @description Replace <code> tags with styled <span> to fix the bug of Edge's translator.
  7. // @description:zh-CN 把网页中的所有内联的<code>标签替换成同样式<span>,以修复Edge内置翻译器bug
  8. // @author yqs112358
  9. // @license MIT
  10. // @match *://*/*
  11. // @grant none
  12. // @run-at document-idle
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17.  
  18. // Replace a single <code> tag with a same-styled <span>
  19. function replaceCodeToSpan(codeNode) {
  20. // only process <code> without any child element
  21. if (codeNode.tagName === 'CODE' && codeNode.children.length === 0) {
  22. const spanNode = document.createElement('span');
  23.  
  24. // Copy all attributes
  25. Array.from(codeNode.attributes).forEach(attr => {
  26. spanNode.setAttribute(attr.name, attr.value);
  27. });
  28. // Copy all computed styles
  29. const computedStyle = window.getComputedStyle(codeNode);
  30. for (let key of computedStyle) {
  31. spanNode.style[key] = computedStyle[key];
  32. }
  33. // Copy InnerHTML
  34. spanNode.innerHTML = codeNode.innerHTML;
  35.  
  36. codeNode.parentNode.replaceChild(spanNode, codeNode);
  37. }
  38. }
  39.  
  40. // Walkthrough a node and its child to replace <code> tags
  41. function processNodeAndChild(node) {
  42. if (node.nodeType === 1) { // Element node
  43. node.querySelectorAll('code').forEach(replaceCodeToSpan);
  44. replaceCodeToSpan(node);
  45. }
  46. }
  47.  
  48. ////////////////////////////////////////////////////////
  49.  
  50. // Replace <code> at startup
  51. document.querySelectorAll('code').forEach(replaceCodeToSpan);
  52.  
  53. // Observe DOM changes and replace new-generated <code> if needed
  54. const observer = new MutationObserver(function(mutations) {
  55. mutations.forEach(function(mutation) {
  56. mutation.addedNodes.forEach(processNodeAndChild);
  57. });
  58. });
  59. observer.observe(document.body, {
  60. childList: true,
  61. subtree: true
  62. });
  63. })();

QingJ © 2025

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