JavaScript Copy Text to Clipboard
You can copy text to the visitor’s clipboard with the modern Clipboard API. It is used for “Copy code” and “Copy link” buttons.
HTML and JavaScript
<input type="text" id="coupon" value="SAVE20" readonly>
<button id="copyBtn">Copy</button>
<span id="status"></span>
<script>
const input = document.getElementById("coupon");
const status = document.getElementById("status");
document.getElementById("copyBtn").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(input.value);
status.textContent = "Copied!";
} catch (error) {
status.textContent = "Could not copy";
}
});
</script>
Output in the browser (after clicking Copy):
Output in the browser
Copied!
How it works
navigator.clipboard.writeText()returns a promise, so we useawait(see async and await).- It works only on secure pages (https or localhost) and after a user action like a click.
- The
try...catchshows a message if the browser blocks it.
To read text from the clipboard use navigator.clipboard.readText(). The browser asks the visitor for permission first.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |