What better code to copy to clipboard that works across browsers?
What better code to copy to clipboard that works across browsers?
This function is a gambiarra that receives a value and automatically copies it to the clipboard. If your browser does not support error handling it calls a secondary function.
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", text);
}
document.body.removeChild(textArea);
}
// Teste
var copyTest = document.querySelector('.copyTest');
copyTest.addEventListener('click', function(event) {
copyTextToClipboard('Teste');
});
<p>
<button class="copyTest">Copiar "Teste"</button>
</p>
<p>
<input type="text" placeholder="Cole aqui">
</p>
It works in the following browsers: Chrome 43+, Firefox 41+, Internet Explorer 10+ and Opera 29+
Notes:
var copySupported = document.queryCommandSupported('copy');
document.execCommand('copy')
is only called if the user makes
some direct action, such as an onClick event for example. This is done
to prevent data from being copied to the clipboard without
the user's intention.
In this option a prompt opens with the value already selected and the user manually copies the code. The advantage is that it works across browsers.
function copyToClipboard(text) {
window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", text);
}