WARNING:
To date, 12/31/2019, in which this response was written this solution is only compatible with browsers based on Chromium, Firefox and Opera. The response is based on technology considered until recently and has not yet been fully implemented between browsers.
W3C | Clipboard API and Events
Can I Use | Clipboard API: writeText
Webkit API Improvements | Clipboard API Improvements
An alternative would be to use Transfer Area API to make a copy of the information.
Your documentation describes you:
To Clipboard API provides the ability to respond to
clipboard commands (cut, copy and paste), plus
asynchronously read and write to the system clipboard.
This API is designed to replace access to the
transfer using document.execCommand()
.
This API adds the interface Navigator
the reading property clipboard
that returns the object Clipboard
used to read and write content to the clipboard.
Remembering that:
Access to clipboard content is blocked behind the
API of permissions ; without the user’s permission, it is not allowed to read or
change content in clipboard.
To save a string to the clipboard use the method writeText()
function copiar() {
let nome = document.getElementById('Nome').innerText;
let sobrenome = document.getElementById('Sobrenome').innerText;
navigator.clipboard.writeText(nome + " " + sobrenome)
.then(
function() {
console.log(" Os dados foram copiados.")
},
function() {
console.error("Houve um problema ao copiar os dados.")
});
}
<div>
<label>Nome:</label>
<span id="Nome">Augusto</span>
</div>
<div>
<label>Sobrenome:</label>
<span id="Sobrenome">Vasques</span>
</div>
<br>
<input type="button" onclick="copiar()" value="Copiar">
Thank you very much for your reply. And, after a lot of research, the solution below also seems feasible, because it selects the copied text, indicating visually to the user the copied data. It’s interesting..
– Daniel