识别文本中的链接

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

  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.2
  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. link.style.color = 'linktext';
  43. link.style.textDecoration = 'underline';
  44. fragment.appendChild(link);
  45.  
  46. lastIndex = index + url.length;
  47. return '';
  48. });
  49.  
  50. if (lastIndex < text.length) {
  51. const remainingText = document.createTextNode(text.slice(lastIndex));
  52. fragment.appendChild(remainingText);
  53. }
  54.  
  55. node.parentNode.replaceChild(fragment, node);
  56. }
  57. }
  58.  
  59. document.addEventListener('selectstart', (event) => {
  60. element = event.target;
  61. });
  62.  
  63. document.addEventListener('mouseup', (event) => {
  64. if (event.button === 0 && element && element.nodeType === Node.TEXT_NODE && element.textContent.trim()) {
  65. processTextNode(element);
  66. element = null;
  67. }
  68. });
  69.  
  70. })();