-
-
Save ten9miq/bd91fc3222c9dd4eaa321f1bb499ca37 to your computer and use it in GitHub Desktop.
Convert URL text to link for Tampermonky
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Text2Link_auto | |
// @namespace | |
// @version 1.2 | |
// @description Link the URL loaded on to linked ! | |
// @updateURL https://gist.githubusercontent.com/ten9miq/bd91fc3222c9dd4eaa321f1bb499ca37/raw/Text2Link.js | |
// @downloadURL https://gist.githubusercontent.com/ten9miq/bd91fc3222c9dd4eaa321f1bb499ca37/raw/Text2Link.js | |
// @author ten9miq | |
// @match http*://*/* | |
// @grant none | |
(function () { | |
("use strict"); | |
/** | |
* @param {HTMLElement} parentElement | |
*/ | |
const text2Link = parentElement => { | |
parentElement = parentElement ?? document.querySelector("body"); | |
parentElement.childNodes.forEach(node => { | |
if (node.nodeType === Node.TEXT_NODE) { | |
const trimmedText = node.textContent.replace(/[\r\n\t ]/, ""); | |
if (trimmedText !== "") { | |
let text = node.textContent; | |
const replaceNodes = []; | |
const regexp = /h?ttps?:\/\/[a-zA-Z0-9#\?=\-_&\.\(\)\^\/\+]+/g; | |
let m; | |
while ((m = regexp.exec(text)) !== null) { | |
const beforeUrl = document.createTextNode(text.substr(0, m.index)); | |
replaceNodes.push(beforeUrl); | |
const link = document.createElement("span"); | |
link.classList.add("Text2Link"); | |
link.setAttribute("data-url", m[0]); | |
link.textContent = m[0]; | |
replaceNodes.push(link); | |
text = text.substr(m.index + m[0].length); | |
if (!text) break; | |
} | |
if (0 < replaceNodes.length) { | |
if (text) replaceNodes.push(document.createTextNode(text)); | |
const parent = node.parentElement; | |
replaceNodes.forEach(n => parent.insertBefore(n, node)); | |
parent.removeChild(node); | |
} | |
} | |
} else if (node.nodeType === Node.ELEMENT_NODE) { | |
if (node.nodeName !== "A" && node.nodeName !== "SCRIPT") | |
text2Link(node); | |
} | |
}); | |
document.querySelectorAll(".Text2Link").forEach(element => { | |
element.childNodes.forEach(n => element.removeChild(n)); | |
const a = document.createElement("a"); | |
a.href = element.getAttribute("data-url"); | |
a.textContent = a.href; | |
element.appendChild(a); | |
}); | |
}; | |
text2Link(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment