AutoLinker

自动将页面所有文本转换为链接

目前為 2021-07-12 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name AutoLinker
  3. // @namespace tea.pm
  4. // @include *
  5. // @grant none
  6. // @version 1.1.3
  7. // @author cljnnn
  8. // @run-at document-idle
  9. // @description 自动将页面所有文本转换为链接
  10. // @description_en translate url in text to link
  11. // ==/UserScript==
  12. String.prototype.isEmpty = function () {
  13. return (this.length === 0 || !this.trim());
  14. };
  15.  
  16. const reUrl = /\b(\w+:\/\/\S*)\b/g;
  17.  
  18. function fixURL(node) {
  19. value = node.nodeValue;
  20. //console.log("updating link... ", node.nodeType, value);
  21. newValue = value.replace(reUrl, '<a target="_blank" href="$1">$1</a>');
  22. var replacementNode = document.createElement('span');
  23. replacementNode.innerHTML = newValue;
  24. node.parentNode.insertBefore(replacementNode, node);
  25. node.parentNode.removeChild(node);
  26. }
  27. function shouldIgnoreNode(node) {
  28. if (!node) return true;
  29. let name = node.nodeName;
  30. return (name == "SCRIPT" || name == "NOSCRIPT" || name == "STYLE" || name == "A" || name == "INPUT" || name == "TEXTAREA");
  31. }
  32. function traverse(node) {
  33. if (!node) return;
  34. if (shouldIgnoreNode(node)) return;
  35. if (node.nodeType == Node.TEXT_NODE) {
  36. let value = node.nodeValue;
  37. if (value && value != "") {
  38. if (value.match(reUrl)) {
  39. fixURL(node)
  40. }
  41. }
  42. }
  43. if (node.nodeType == Node.ELEMENT_NODE) {
  44. for (let child of node.childNodes) {
  45. traverse(child);
  46. }
  47. }
  48. }
  49.  
  50. function action(changes, observer) {
  51. for (let mutation of changes) {
  52. if (mutation.type !== 'childList') {
  53. continue;
  54. }
  55. if (shouldIgnoreNode(mutation.target)) continue;
  56. for (let node of mutation.addedNodes) {
  57. traverse(node);
  58. }
  59. }
  60. }
  61.  
  62. var observer = new MutationObserver(action);
  63. observer.observe(document, { childList: true, subtree: true });
  64. traverse(document.body);

QingJ © 2025

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