Use the navigator.clipboard API to read and write text to the clipboard.
// Write to clipboard when .write-to-clipboard clicked
document.querySelector(".write-to-clipboard").addEventListener("click", (e) => {
const text = "Text from clipboard.";
navigator.clipboard.writeText(text).then(
function () {
console.log("Text copied in clipboard.");
},
function () {
console.error("Clipboard write permission denied.");
}
);
});
// Read from clipboard when .read-from-clipboard clicked
document.querySelector(".read-from-clipboard").addEventListener("click", (e) => {
navigator.clipboard.readText().then((text) => {
console.log("Text read from clipboard.", text);
});
});