Skip to content

Instantly share code, notes, and snippets.

@andy128k
Last active May 13, 2020 18:43
Show Gist options
  • Save andy128k/e876ce6e605e10fe20ef0578ce979752 to your computer and use it in GitHub Desktop.
Save andy128k/e876ce6e605e10fe20ef0578ce979752 to your computer and use it in GitHub Desktop.
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);
}
}())
@andy128k
Copy link
Author

This is a bookmarklet which adds a button next to all <table>s for copying its content as a CSV.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment