识别文本中的链接

点击网页文本中的URL并将其转换为可点击的链接

当前为 2025-02-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Detect Links in Text
  3. // @name:zh-CN 识别文本中的链接
  4. // @name:zh-TW 識別文本中的鏈接
  5. // @namespace http://tampermonkey.net/
  6. // @version 0.1
  7. // @description Click on URLs within webpage text and convert them into clickable links.
  8. // @description:zh-CN 点击网页文本中的URL并将其转换为可点击的链接
  9. // @description:zh-TW 點擊網頁文本中的URL並將其轉換為可點擊的鏈接
  10. // @author yinlili
  11. // @include *
  12. // @icon https://img.icons8.com/external-tal-revivo-fresh-tal-revivo/28/external-online-web-link-attach-with-url-information-text-fresh-tal-revivo.png
  13. // @grant none
  14. // @license MIT
  15. // ==/UserScript==
  16.  
  17. (() => {
  18. 'use strict';
  19.  
  20. const urlPattern = /https?:\/\/(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(?:\/(?:[-\w.!$&*+~]|%[0-9A-Fa-f]{2})*)*(?:\?(?:[-._~!$&'()*+,;=:@\/?a-zA-Z0-9]|%[0-9A-Fa-f]{2})*)?(?:#(?:[-._~!$&'()*+,;=:@\/?a-zA-Z0-9]|%[0-9A-Fa-f]{2})*)?/g;
  21.  
  22. let element;
  23.  
  24. function processTextNode(node) {
  25. const text = node.textContent;
  26.  
  27. if (urlPattern.test(text)) {
  28.  
  29. const fragment = document.createDocumentFragment();
  30. let lastIndex = 0;
  31.  
  32. text.replace(urlPattern, (url, index) => {
  33. if (index > lastIndex) {
  34. const nonUrlPart = document.createTextNode(text.slice(lastIndex, index));
  35. fragment.appendChild(nonUrlPart);
  36. }
  37.  
  38. const link = document.createElement('a');
  39. link.href = url;
  40. link.target = '_blank';
  41. link.textContent = url;
  42. fragment.appendChild(link);
  43.  
  44. lastIndex = index + url.length;
  45. return '';
  46. });
  47.  
  48. if (lastIndex < text.length) {
  49. const remainingText = document.createTextNode(text.slice(lastIndex));
  50. fragment.appendChild(remainingText);
  51. }
  52.  
  53. node.parentNode.replaceChild(fragment, node);
  54. }
  55. }
  56.  
  57. document.addEventListener('selectstart', (event) => {
  58. element = event.target;
  59. });
  60.  
  61. document.addEventListener('mouseup', (event) => {
  62. if (element.nodeType === Node.TEXT_NODE && element.textContent.trim()) {
  63. processTextNode(element);
  64. }
  65. });
  66.  
  67. })();