Linkify

Turn plain-text URLs into hyperlinks

  1. // ==UserScript==
  2.  
  3. // @name Linkify
  4. // @version 0.1
  5. // @namespace http://youngpup.net/userscripts
  6.  
  7. // @description Turn plain-text URLs into hyperlinks
  8.  
  9. // @include *
  10.  
  11. // ==/UserScript==
  12.  
  13.  
  14.  
  15. // based on code by Aaron Boodman
  16.  
  17. // and included here with his gracious permission
  18.  
  19.  
  20.  
  21. var urlRegex = /\b(https?:\/\/[^\s+\"\<\>]+)/ig;
  22.  
  23. var snapTextElements = document.evaluate("//text()[not(ancestor::a) " +
  24.  
  25. "and not(ancestor::script) and not(ancestor::style) and " +
  26.  
  27. "contains(translate(., 'HTTP', 'http'), 'http')]",
  28.  
  29. document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  30.  
  31. for (var i = snapTextElements.snapshotLength - 1; i >= 0; i--) {
  32.  
  33. var elmText = snapTextElements.snapshotItem(i);
  34.  
  35. if (urlRegex.test(elmText.nodeValue)) {
  36.  
  37. var elmSpan = document.createElement("span");
  38.  
  39. var sURLText = elmText.nodeValue;
  40.  
  41. elmText.parentNode.replaceChild(elmSpan, elmText);
  42.  
  43. urlRegex.lastIndex = 0;
  44.  
  45. for (var match = null, lastLastIndex = 0;
  46.  
  47. (match = urlRegex.exec(sURLText)); ) {
  48.  
  49. elmSpan.appendChild(document.createTextNode(
  50.  
  51. sURLText.substring(lastLastIndex, match.index)));
  52.  
  53. var elmLink = document.createElement("a");
  54.  
  55. elmLink.setAttribute("href", match[0]);
  56.  
  57. elmLink.appendChild(document.createTextNode(match[0]));
  58.  
  59. elmSpan.appendChild(elmLink);
  60.  
  61. lastLastIndex = urlRegex.lastIndex;
  62.  
  63. }
  64.  
  65. elmSpan.appendChild(document.createTextNode(
  66.  
  67. sURLText.substring(lastLastIndex)));
  68.  
  69. elmSpan.normalize();
  70.  
  71. }
  72.  
  73. }