Clipboard API
Reading from and writing to the system clipboard — copy, cut, paste, rich content, and the legacy document.execCommand fallback.
What it is, in plain English: The Clipboard API provides modern, permission-based access to the system clipboard. navigator.clipboard.writeText(text) copies text programmatically. navigator.clipboard.readText() reads the clipboard (requires permission). The ClipboardItem interface supports rich content — HTML, images, and custom MIME types. For simple copy-to-clipboard buttons, writeText() is all you need.
Copy and paste from JavaScript
Copy text to clipboard
// The simplest pattern — copy any text:
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log("Copied!");
} catch (error) {
console.error("Copy failed:", error);
}
}
// A copy button that gives feedback:
const copyBtn = document.querySelector("#copy-btn");
const codeEl = document.querySelector("pre");
copyBtn.addEventListener("click", async () => {
await navigator.clipboard.writeText(codeEl.textContent);
copyBtn.textContent = "✓ Copied!";
setTimeout(() => { copyBtn.textContent = "Copy"; }, 2000);
});Reading the clipboard
// Reading requires user permission (browser asks):
async function pasteText() {
try {
const text = await navigator.clipboard.readText();
input.value = text; // paste into an input
} catch (error) {
// User denied or clipboard access not available
console.error(error.message);
}
}
// Listen for paste events (no permission needed — user initiates):
document.addEventListener("paste", (event) => {
const text = event.clipboardData.getData("text/plain");
console.log("User pasted:", text);
event.preventDefault(); // prevent default paste behaviour
});
Try It Yourself
Official Sources
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.