4
Which code to copy to clipboard works best in all browsers?
4
Which code to copy to clipboard works best in all browsers?
5
This function is a function that receives a value and automatically copies it to the clipboard. If your browser does not support error handling 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>
Works on 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
some direct action, such as an onClick event for example. This is done
to prevent data from being copied to the clipboard without
the intention of the user.This option opens a prompt with the value already selected and the user manually copies the code. The advantage is that it works in all browsers.
function copyToClipboard(text) {
window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", text);
}
Browser other questions tagged javascript clipboard
You are not signed in. Login or sign up in order to post.
1)Cross-browser way of copying text to the Clipboard Clipboard, 2)[How to copy to clipboard without using flash? ] (http://answall.com/q/81098/91), 3) How can I copy an image to the clipboard?, 4) How do I take what’s copied in the clipboard and put in a variable?, 5) others
– rray
You might consider my answer?
– Slowaways
Don’t understand? if solved the problem clear that the answer is valid.
– rray