Javascript Clipboard API
References
Examples
To copy to clipboard:
navigator.clipboard.writeText(newClip)
Or more fully (example from mozilla)
function updateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
/* clipboard successfully set */
},
() => {
/* clipboard write failed */
},
);
}
To paste from clipboard (from mozilla docs):
navigator.clipboard
.readText()
.then((clipText) => (document.getElementById("outbox").innerText = clipText));
Old School Method
If not on https, then the clipboard API is not available. There is an old technique which still works. Often I have things on my LAN where I want to copy, and it is annoying to have to manually add machines to a Chrome whitelist (on each machine I use), and then put up with the resulting nagging about treating insecure sites as secure.
function docopy(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('Unable to copy to clipboard', err);
}
document.body.removeChild(textArea);
}