Convert Any links to Clickable Links

Convert plain text URLs and domain names (even missing "h" for http/https) into clickable links

目前為 2025-02-23 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Convert Any links to Clickable Links
  3. // @namespace kdroidwin.hatenablog.com/
  4. // @version 1.1
  5. // @description Convert plain text URLs and domain names (even missing "h" for http/https) 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. // 正規表現パターンを更新: "h" がない場合や "http(s)://" の場合も対象にする
  16. // この例では先頭が "h?ttps?://" を探すことで、"h" がない場合にもマッチする
  17. const pattern = /(h?ttps?:\/\/[^\s]+|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})/g;
  18. const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
  19. acceptNode: node => {
  20. // この部分も正規表現を更新(元のコードとほぼ同じですが、patternを使用)
  21. if (node.parentNode && node.parentNode.tagName !== 'A' && pattern.test(node.nodeValue)) {
  22. return NodeFilter.FILTER_ACCEPT;
  23. }
  24. return NodeFilter.FILTER_REJECT;
  25. }
  26. });
  27. let nodes = [];
  28. while (walker.nextNode()) {
  29. nodes.push(walker.currentNode);
  30. }
  31. nodes.forEach(node => {
  32. const fragment = document.createDocumentFragment();
  33. // 改良:正規表現のキャプチャを利用して分割(splitはキャプチャも含むのでOK)
  34. const parts = node.nodeValue.split(pattern);
  35. parts.forEach(part => {
  36. // "ttps://" で始まる場合には先頭に"h"を補給
  37. if (/^ttps:\/\//i.test(part)) {
  38. const link = document.createElement('a');
  39. link.href = 'h' + part;
  40. link.textContent = part;
  41. link.target = '_blank';
  42. fragment.appendChild(link);
  43. // "http://" または "https://" で始まる場合
  44. } else if (/^https?:\/\//i.test(part)) {
  45. const link = document.createElement('a');
  46. link.href = part;
  47. link.textContent = part;
  48. link.target = '_blank';
  49. fragment.appendChild(link);
  50. // ドメインパターン
  51. } else if (/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/.test(part)) {
  52. const link = document.createElement('a');
  53. link.href = 'https://' + part;
  54. link.textContent = part;
  55. link.target = '_blank';
  56. fragment.appendChild(link);
  57. } else {
  58. fragment.appendChild(document.createTextNode(part));
  59. }
  60. });
  61. node.parentNode.replaceChild(fragment, node);
  62. });
  63. }
  64.  
  65. convertTextToLinks();
  66. new MutationObserver(convertTextToLinks).observe(document.body, { childList: true, subtree: true });
  67. })();