Link Wrapper

Wraps links with specified protocols in <a> tags.

  1. // ==UserScript==
  2. // @name Link Wrapper
  3. // @author TM
  4. // @namespace https://trap.jp/
  5. // @version 0.1
  6. // @description Wraps links with specified protocols in <a> tags.
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. var regexp_url = /((h?)(ttps?:\/\/[a-zA-Z0-9.\-_@:/~?%&;=+#',()*!]+))/g;
  16.  
  17. var wrapLink = function(all, url, h, href) {
  18. return '<a href="h' + href + '" target="_blank">' + url + '</a><br/>';
  19. }
  20.  
  21. /**
  22. * 渡されるコンテンツ:
  23. * - <div>hoge<div>...<div>fuga</div>
  24. * <div>hogefuga</div>
  25. */
  26. function wrapLinks(element) {
  27. var textContent = "";
  28. if(element.nodeType === 3) {
  29. textContent = element.textContent;
  30. }
  31. else{
  32. for(var elem of element.childNodes){
  33. console.log(elem);
  34. console.log(elem.nodeType);
  35. if(elem.nodeType === 3) {
  36. textContent += elem.textContent;
  37. }
  38. }
  39. }
  40. if (textContent) {
  41. var newTextContent = textContent.replace(regexp_url, wrapLink);
  42. if (newTextContent !== textContent) {
  43. element.innerHTML = newTextContent;
  44. }
  45. }
  46. }
  47.  
  48. function traverseAndWrap(element) {
  49. if(element.tagName === "A" || element.tagName === "STYLE" || element.tagName === "SCRIPT"){
  50. return;
  51. }
  52. if (element.childNodes.length === 1) {
  53. console.log(element);
  54. wrapLinks(element);
  55. }
  56.  
  57. for (var i = 0; i < element.childNodes.length; i++) {
  58. var childNode = element.childNodes[i];
  59. if (childNode.nodeType === 1) {
  60. traverseAndWrap(childNode);
  61. }
  62. }
  63.  
  64. }
  65.  
  66. window.addEventListener('load', function() {
  67. traverseAndWrap(document.body);
  68. });
  69. })();