Last active
May 13, 2020 18:43
-
-
Save andy128k/e876ce6e605e10fe20ef0578ce979752 to your computer and use it in GitHub Desktop.
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
javascript:(function() { | |
function clean(str) { | |
return (str || '').replace(/\s+/g, ' ').trim(); | |
} | |
function quote(str) { | |
return '"' + str.replace(/"/g, '""') + '"'; | |
} | |
function getCsv(table) { | |
let csv = []; | |
for (let row of table.querySelectorAll('tr')) { | |
let csv_row = []; | |
for (let cell of row.querySelectorAll('th, td')) { | |
csv_row.push(quote(clean(cell.textContent))); | |
} | |
csv.push(csv_row.join(',')); | |
} | |
return csv.join('\n'); | |
} | |
for (let table of document.querySelectorAll('table')) { | |
let c = document.createElement('button'); | |
c.style.margin = '10px 10px 10px 10px'; | |
c.style.padding = '5px 10px 5px 10px'; | |
c.style.background = '#fcc'; | |
c.style.color = 'black'; | |
c.style.border = "1px solid 'black'"; | |
c.innerHTML = 'Copy CSV into clipboard'; | |
let table_el = table; | |
c.addEventListener('click', () => { | |
let csv = getCsv(table_el); | |
navigator.clipboard.writeText(csv).then(function() { | |
alert('Table is copied into clipboard'); | |
}, function() { | |
alert('Error'); | |
}) | |
}); | |
table.parentNode.insertBefore(c, table); | |
} | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a bookmarklet which adds a button next to all
<table>
s for copying its content as a CSV.