Skip to content

Instantly share code, notes, and snippets.

@paulroth3d
Last active June 19, 2021 04:28
Show Gist options
  • Save paulroth3d/ce29a97f5855bd4ff735e903937623cc to your computer and use it in GitHub Desktop.
Save paulroth3d/ce29a97f5855bd4ff735e903937623cc to your computer and use it in GitHub Desktop.

Overview

This puts a table from a web page into the clipboard (as Tab Separated Values)

This means you can effectively: select within a table, click a button and then paste it into a spreadsheet.

Requirements

(This may work on other browsers, feedback welcome)

  • Google Chrome - main focus

Install

  • Create a new Bookmark
  • Paste the compileBookmarklet.js contents as the targetURL

To Use

  • select anything within a table you want to copy
    • (This is to indicate which table we want to copy)
  • click the bookmark you created
  • go to a spreadsheet you want to apply the bookmark to and select a cell
  • paste

To Install

Download from https://paulroth3d.github.io

compiling

note that we had to use the %22 for doublequotes (") in the source. There is a bug in the Boolmarklet generator

Find the escape function and ensure that the '); is there for all lines and not missing.

Then you'll need to url encode it for the link

Further Reading / Sources

javascript: (function() {
function getSelectedNode() {
if (document.selection) return document.selection.createRange().parentElement();
else {
var selection = window.getSelection();
if (selection.rangeCount > 0) return selection.getRangeAt(0).startContainer.parentNode;
}
}
function copyToClipboard(text) {
try {
if (window.clipboardData && window.clipboardData.setData) {
return clipboardData.setData('Text', text);
} else if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
try {
navigator.clipboard.writeText(text);
return;
} catch (ex) {}
var textarea = document.createElement('textarea');
textarea.textContent = text;
textarea.style.position = 'fixed';
textarea.style.left = '-999999px';
textarea.style.top = '-999999px';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
return new Promise((response, reject) => {
try {
document.execCommand('copy') ? response() : reject();
textarea.remove();
} catch (err) {
console.warn('copy attempt 2 failed', err);
}
});
} else {
alert('No copy feature available in this context');
}
} catch (err) {
console.error('copy to clipboard failed', err);
alert('copy to clipboard failed');
}
}
function tableToArray(currentTable) {
return Array.from(currentTable.querySelectorAll('tr')).map(trEl => Array.from(trEl.querySelectorAll('td,th')).map(tdEl => tdEl.innerText))
}
function escapeCell(val) {
let val2 = (val || '');
val2 = val2.replace(/([\t'])/g, '\\$1');
val2 = val2.replace(/%22/g, '%22%22');
val2 = val2.replace(/\n/g, '\\n');
return `%22${val2}%22`;
}
function tableToTSV(tableArray) {
return tableArray.map(row => row.map(escapeCell).join('\t')).join('\n');
}
var selectedElement = getSelectedNode();
var selectedTable = selectedElement ? selectedElement.closest('table') : null;
if (!selectedTable) {
alert('No selection found. Please select within the table to copy');
}
copyToClipboard(tableToTSV(tableToArray(selectedTable)));
})();
javascript:(function(){function getSelectedNode(){if(document.selection)return document.selection.createRange().parentElement();else{var selection=window.getSelection();if(selection.rangeCount>0)return selection.getRangeAt(0).startContainer.parentNode;}}function copyToClipboard(text){try{if(window.clipboardData&&window.clipboardData.setData){return clipboardData.setData('Text',text);}else if(document.queryCommandSupported&&document.queryCommandSupported('copy')){try{navigator.clipboard.writeText(text);return;}catch(ex){}var textarea=document.createElement('textarea');textarea.textContent=text;textarea.style.position='fixed';textarea.style.left='-999999px';textarea.style.top='-999999px';document.body.appendChild(textarea);textarea.focus();textarea.select();return new Promise((response,reject)=>{try{document.execCommand('copy')?response():reject();textarea.remove();}catch(err){console.warn('copy attempt 2 failed',err);}});}else{alert('No copy feature available in this context');}}catch(err){console.error('copy to clipboard failed',err);alert('copy to clipboard failed');}}function tableToArray(currentTable){return Array.from(currentTable.querySelectorAll('tr')).map(trEl=>Array.from(trEl.querySelectorAll('td,th')).map(tdEl=>tdEl.innerText))}function escapeCell(val){let val2=(val||'');val2=val2.replace(/([\t'])/g, '\\$1'); val2=val2.replace(/%22/g,'%22%22');val2=val2.replace(/\n/g,'\\n');return `%22${val2}%22`;}function tableToTSV(tableArray){return tableArray.map(row=>row.map(escapeCell).join('\t')).join('\n');}var selectedElement=getSelectedNode();var selectedTable=selectedElement?selectedElement.closest('table'):null;if(!selectedTable){alert('No selection found. Please select within the table to copy');}copyToClipboard(tableToTSV(tableToArray(selectedTable)));})();
javascript:(function()%7Bfunction getSelectedNode()%7Bif(document.selection)return document.selection.createRange().parentElement()%3Belse%7Bvar selection%3Dwindow.getSelection()%3Bif(selection.rangeCount>0)return selection.getRangeAt(0).startContainer.parentNode%3B%7D%7Dfunction copyToClipboard(text)%7Bif(window.clipboardData%26%26window.clipboardData.setData)%7Breturn clipboardData.setData("Text",text)%3B%7Delse if(document.queryCommandSupported%26%26document.queryCommandSupported("copy"))%7Bvar textarea%3Ddocument.createElement("textarea")%3Btextarea.textContent%3Dtext%3Btextarea.style.position%3D"fixed"%3Bdocument.body.appendChild(textarea)%3Btextarea.select()%3Btry%7Bnavigator.clipboard.writeText(text)%3B%7Dcatch(ex)%7Bconsole.warn("Copy to clipboard failed.",ex)%3Breturn false%3B%7Dfinally%7Bdocument.body.removeChild(textarea)%3B%7D%7D%7Dfunction tableToTSV(currentTable)%7Breturn Array.from(currentTable.querySelectorAll(%27tr%27)).map(trEl%3D>Array.from(trEl.querySelectorAll(%27td,th%27)).map(tdEl%3D>tdEl.innerText).join(%27%5Ct%27)).join(%27%5Cn%27)%3B%7Dvar selectedElement%3DgetSelectedNode()%3Bif(!selectedElement)%7Balert(%27No selection found. Please select within the table to copy%27)%3Breturn%3B%7DcopyToClipboard(tableToTSV(selectedElement.closest(%27table%27)))%3B%7D)()%3B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment