Clean β’ Professional
The Clipboard API allows web applications to interact with the system clipboard, enabling reading from and writing to it. It is a modern browser API that replaces older execCommand methods, providing a safer and more reliable way to handle clipboard operations.
Note: Clipboard operations usually require user interaction (like a click or keypress) and must run on HTTPS for security reasons.
writeText().readText(), if permitted.The writeText() method writes a string to the clipboard.
navigator.clipboard.writeText("Hello World!")
.then(() => console.log("Text copied!"))
.catch((err) => console.error("Failed to copy text:", err));
Example: Copy Button
<input type="text" id="myText" value="Hello World!">
<button id="copyBtn">Copy Text</button>
<script>
const copyBtn = document.getElementById("copyBtn");
const input = document.getElementById("myText");
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(input.value)
.then(() => alert("Text copied!"))
.catch(err => console.error("Failed:", err));
});
</script>
The readText() method reads plain text from the clipboard.
navigator.clipboard.readText()
.then(text => console.log("Clipboard text:", text))
.catch(err => console.error("Failed to read clipboard:", err));
Example: Paste Button
<button id="pasteBtn">Paste Text</button>
<p id="output">Clipboard text will appear here</p>
<script>
const pasteBtn = document.getElementById("pasteBtn");
const output = document.getElementById("output");
pasteBtn.addEventListener("click", async () => {
try {
const text = await navigator.clipboard.readText();
output.textContent = text;
} catch (err) {
console.error("Failed to read clipboard:", err);
}
});
</script>
<input type="text" id="inputText" placeholder="Type something">
<button id="copy">Copy</button>
<button id="paste">Paste</button>
<p id="display"></p>
<script>
const input = document.getElementById("inputText");
const display = document.getElementById("display");
document.getElementById("copy").addEventListener("click", () => {
navigator.clipboard.writeText(input.value)
.then(() => alert("Copied!"));
});
document.getElementById("paste").addEventListener("click", async () => {
try {
const text = await navigator.clipboard.readText();
display.textContent = text;
} catch (err) {
console.error("Cannot read clipboard:", err);
}
});
</script>
Copy button β saves input text to clipboard.Paste button β retrieves clipboard text and displays it on the page.