|
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))); |
|
})(); |