My goal is to make a function that, on a specific page, collects data and copies it to the clipboard, later pasted into a Google Sheet or Excel Spreadsheet.
The data appears in different places on a web-page and is presented as follows:
<!-- Somewhere throughout the web page -->
<div data-cy="a">
<strong><a href="www.example.com">text</a></strong>
</div>
<!-- Another place throughout the web page -->
<div data-cy="b">
<strong>another text</strong>
</div>
Moreover, I need to push some of my simple strings, such as var text = 'different text'.
In an Excel spreadsheet, the three values should be pasted in three matching fields in one row:
| A | B | C | |
|---|---|---|---|
| 1 | text | another text | different text |
Here is my code so far:
var a = $('*[data-cy="a"]').html().replaceAll('\n','').replaceAll('<strong>','').replaceAll('</strong>','') // extract 'a'.
var b = $('*[data-cy="b"]').html().replaceAll('\n','').split(/[><]/)[2]; // extract 'b'.
var c = 'different text';
var allCells = a + '\t' + b + '\t' + c; // using Tab character to divide between cells.
function copyToClipboard(str) {
function listener(e) {
e.clipboardData.setData("text/html", str);
e.clipboardData.setData("text/plain", str);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
};
copyToClipboard(allCells);
I tried both the deprecated and more recent versions of navigator.clipboard.writeText(), but none of these seem to give me the option to paste the values in different cells in the same row.
This comment helped me to figure out what is actually happening. In order to work around this, unfortunately, I created a new table in the DOM and copied the elements from there. Pasting into the Excel sheet works like a charm.
// Extraction of variables
var a = $('*[data-cy="a"]').html().replaceAll('\n','').replaceAll('<strong>','').replaceAll('</strong>','') // extract 'a'.
var b = $('*[data-cy="b"]').html().replaceAll('\n','').split(/[><]/)[2]; // extract 'b'.
var c = 'different text';
let allCells = [$(clientName), locationCompany, treatedBy];
// Table creation
var table = $('<table>').addClass('table').attr('id', 'excel-data');
var row = $('<tr>');
for(i=0; i<allCells.length; i++) {
row.append($('<td>').html(allCells[i]));
}
table.append(row);
$('[data="element-data"]').append(table);
// Select & copy table function
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
document.execCommand("copy");
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand("Copy");
}
}