Clipboard API
The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. It replaces the older, synchronous document.execCommand() method.
1. Writing to the Clipboard
The most common operation is copying text to the clipboard. This is done using navigator.clipboard.writeText().
async function copyTextToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
const copyBtn = document.querySelector('#copy');
copyBtn.addEventListener('click', () => {
copyTextToClipboard('Hello World');
});
2. Reading from the Clipboard
You can read text from the clipboard using navigator.clipboard.readText(). This usually requires the user to grant permission.
async function getClipboardText() {
try {
const text = await navigator.clipboard.readText();
console.log('Clipboard text:', text);
} catch (err) {
console.error('Failed to read clipboard: ', err);
}
}
3. Handling Images and Other Data
The API also supports arbitrary data (like images) using write() and read(). These methods work with ClipboardItem objects.
Copying an Image (Blob)
async function copyImage(blob) {
try {
const item = new ClipboardItem({ [blob.type]: blob });
await navigator.clipboard.write([item]);
console.log('Image copied!');
} catch (err) {
console.error(err);
}
}
// Example: Fetch an image and copy it
fetch('image.png')
.then(response => response.blob())
.then(copyImage);
4. Permissions
The Clipboard API is gated by the Permissions API.
- Writing: Usually allowed automatically when triggered by a user gesture (like a click).
- Reading: Requires explicit permission (
clipboard-read). The browser will prompt the user.
programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/promises-async-await