Created
January 4, 2021 19:31
-
-
Save draqoon/0a79d54582918d3642942c70f69fc3b1 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 | |
// @namespace http://www.sanno-net.com/text2link | |
// @version 1.0 | |
// @description try to take over the world! | |
// @author You | |
// @match https://teratail.com/* | |
// @grant none | |
// ==/UserScript== | |
(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 = /https?:\/\/[a-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); | |
} | |
}); | |
}; | |
text2Link(); | |
document.addEventListener("keydown", e => { | |
if ((e.key === "Control" || e.key === "Shift") && !e.repeat) { | |
if (e.ctrlKey || e.shiftKey) { | |
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); | |
}); | |
} | |
} | |
}); | |
document.addEventListener("keyup", e => { | |
if (e.key === "Control" || e.key === "Shift") { | |
if (!e.ctrlKey && !e.shiftKey) { | |
document.querySelectorAll(".Text2Link").forEach(element => { | |
element.childNodes.forEach(n => element.removeChild(n)); | |
element.textContent = element.getAttribute("data-url"); | |
}); | |
} | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment