文本链接自动识别为超链接

通过正则表达式识别文本中的链接,并转换为超链接

  1. // ==UserScript==
  2. // @name Textlink to Hyperlink
  3. // @name:zh-CN 文本链接自动识别为超链接
  4. // @version 0.1.6
  5. // @description Recognize links in text by regular expression, and convert to hyperlinks
  6. // @description:zh-CN 通过正则表达式识别文本中的链接,并转换为超链接
  7. // @author DreamNya
  8. // @match *://*/*
  9. // @grant none
  10. // @run-at document-start
  11. // @license MIT
  12. // @namespace https://gf.qytechs.cn/users/809466
  13. // ==/UserScript==
  14.  
  15. //最大识别次数,默认5次,可修改,每个节点识别次数超过限制后自动忽略(针对一些冲突节点)
  16. const formatLimit = 5;
  17. const formatList = new WeakMap();
  18.  
  19. //文本链接识别正则
  20. const reg = /https?:\/\/[\w\.-]+\.\w+(:\d{1,5})?(\/[#%\w?&.=\-@]+)*/g;
  21. //忽略标签类型
  22. const ignore = ['SCRIPT', 'STYLE', 'A', 'TEXTAREA', 'NOSCRIPT', 'CODE', 'TITLE'];
  23.  
  24. //脚本运行时遍历所有节点
  25. QueryElement(document);
  26.  
  27. //后续通过观察器监视
  28. let obs = new MutationObserver(m => {
  29. m.forEach(mm => {
  30. FormatHref(mm.target, mm.addedNodes)
  31. mm.addedNodes.forEach(i => QueryElement(i))
  32. })
  33. });
  34. obs.observe(document, { subtree: true, childList: true });
  35.  
  36. function QueryElement(element) {
  37. //用了点语法糖
  38. [...(element.querySelectorAll?.("*") ?? [])].forEach(i => FormatHref(i, i.childNodes))
  39. }
  40.  
  41. function FormatHref(target, childNodes) {
  42. //忽略标签
  43. if (ignore.find(n => n == target.nodeName) || target.translate == false) return
  44.  
  45. //超过次数限制忽略
  46. let formatTimes = formatList.get(target) || 0
  47. if (formatTimes > formatLimit) return
  48.  
  49. let mark = false;
  50.  
  51. //文本链接构造为a标签
  52. [...childNodes].forEach(c => {
  53. if (c.nodeName == '#text' && c.textContent.match(reg)) {
  54. console.log(target, c.textContent)
  55. c.textContent = c.textContent.replace(reg, (m) => { return `<a href='${m}' target='_blank'>${m}</a>` })
  56. mark = true
  57. }
  58. })
  59.  
  60. //格式化标签
  61. if (mark) {
  62. //console.log(target,target.nodeName, formatTimes)
  63. formatList.set(target, formatTimes + 1)
  64. target.innerHTML = target.innerHTML.replace(/&lt;a /g, "<a ").replace(/&lt;\/a&gt;/g, "</a>").replace(/' target='_blank'&gt;/g, "' target='_blank'>")
  65. }
  66. }

QingJ © 2025

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