Reputation: 483
I'm trying to figure out, how to copy string and paste from JavaScript.
This code example:
function copyLink() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
}
Copies from myInput
value
:
<input type="text" value="ttps://site.org/" id="myInput">
but I'm trying copy text from variable, not included to html
value
:
<button onclick="copyText()">Copy text</button>
which is in .js
to allow user copy/paste:
function copyText() {
var text = "long text...";
...
}
It looks simple, but seems like I'm searching incorrectly, because I can't find the method.
Upvotes: 0
Views: 2082
Reputation: 2514
You can use the Async Clipboard API:
async function copy() {
try {
await navigator.clipboard.writeText(input.value);
console.log('Value copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
For more details, please see this article.
Upvotes: 0
Reputation: 13672
As a quick fix, you could just stick the value you want to copy into an input field (even a hidden one), and copy the same way.
Here's a Codepen example: https://codepen.io/kshetline/pen/ExKwjjq?editors=1111
function copyText() {
document.getElementById('hidden').value = new Date().toLocaleString();
var copyText = document.getElementById('hidden');
copyText.select();
document.execCommand('copy');
}
<input id="hidden" type="text" style="opacity: 0; position: absolute; top: -5em">
<button type="button" onclick="copyText()">Copy</button><br>
<label for="paste">Paste here: <input id="paste" type="text"></label>
There's a more advanced API for clipboard operations, however, that's described in this article: https://web.dev/async-clipboard/
Upvotes: 1
Reputation: 770
The best way is to create a Dummy element, copy the content and remove it from the dom.
// Create a dummy input
var dummy = document.createElement("input");
// Inject the content
dummy.value=copyText;
// Add it to the dom
document.body.appendChild(dummy);
// Select it
dummy.select();
// Copy the content
document.execCommand("copy");
// Clean the dom
document.body.removeChild(dummy);
Upvotes: 1