Convert Any links to Clickable Links

Convert plain text URLs and domain names into clickable links

目前为 2025-02-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Convert Any links to Clickable Links
  3. // @namespace kdroidwin.hatenablog.com/
  4. // @version 1.0
  5. // @description Convert plain text URLs and domain names into clickable links
  6. // @author Kdroidwin
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() { 'use strict';
  13.  
  14. function convertTextToLinks() {
  15. const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
  16. acceptNode: node => {
  17. if (node.parentNode && node.parentNode.tagName !== 'A' && /(https?:\/\/[^\s]+|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})/.test(node.nodeValue)) {
  18. return NodeFilter.FILTER_ACCEPT;
  19. }
  20. return NodeFilter.FILTER_REJECT;
  21. }
  22. });
  23. let nodes = [];
  24. while (walker.nextNode()) {
  25. nodes.push(walker.currentNode);
  26. }
  27. nodes.forEach(node => {
  28. const fragment = document.createDocumentFragment();
  29. const parts = node.nodeValue.split(/(https?:\/\/[^\s]+|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})/g);
  30. parts.forEach(part => {
  31. if (/https?:\/\//.test(part)) {
  32. const link = document.createElement('a');
  33. link.href = part;
  34. link.textContent = part;
  35. link.target = '_blank';
  36. fragment.appendChild(link);
  37. } else if (/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/.test(part)) {
  38. const link = document.createElement('a');
  39. link.href = 'https://' + part;
  40. link.textContent = part;
  41. link.target = '_blank';
  42. fragment.appendChild(link);
  43. } else {
  44. fragment.appendChild(document.createTextNode(part));
  45. }
  46. });
  47. node.parentNode.replaceChild(fragment, node);
  48. });
  49. }
  50.  
  51. convertTextToLinks();
  52. new MutationObserver(convertTextToLinks).observe(document.body, { childList: true, subtree: true });
  53.  
  54. })();
  55.