Last active
July 5, 2024 02:37
-
-
Save helloint/e360d2f631e719bb8ec1d06ff208d8c2 to your computer and use it in GitHub Desktop.
Convert URLs from plain text to links
This file contains 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 Convert URLs from plain text to links | |
// @namespace https://helloint.com | |
// @version 0.3 | |
// @description GitHub supports rendering CSV file, but it doesn't support links. This script will find the URLs and convert to links. | |
// @author Wayne Mao | |
// @match https://github.com/**/*.csv | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=web.app | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
const observer = new MutationObserver(mutationsList => { | |
mutationsList.forEach(mutation => { | |
if (mutation.type === 'childList') { | |
const addedNodes = Array.from(mutation.addedNodes); | |
addedNodes.forEach(node => { | |
if (node.classList && node.classList.contains('react-csv-row')) { | |
handleCSVRow(node); | |
} | |
if (node.classList && node.classList.contains('position-relative')) { | |
// 初始化时会一次性添加一批row | |
const rows = node.querySelectorAll('.react-csv-row'); | |
rows.forEach(row => handleCSVRow(row)); | |
} | |
}); | |
} | |
}); | |
}); | |
observer.observe(document.body, { childList: true, subtree: true }); | |
function handleCSVRow(row) { | |
const csvCells = row.querySelectorAll('.react-csv-cell'); | |
csvCells.forEach(cell => { | |
const content = cell.textContent.trim(); | |
if (isValidURL(content)) { | |
const link = document.createElement('a'); | |
link.href = content; | |
link.target = '_blank'; | |
link.textContent = content; | |
cell.innerHTML = ''; | |
cell.appendChild(link); | |
} | |
}); | |
} | |
function isValidURL(str) { | |
try { | |
new URL(str); | |
return true; | |
} catch (_) { | |
return false; | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment