HTML Clipboard API
Copy and paste content programmatically
📋 What is the Clipboard API?
The Clipboard API allows web applications to read from and write to the system clipboard. Perfect for copy/paste functionality in web apps.
// Copy text to clipboard
await navigator.clipboard.writeText('Hello, Clipboard!');
// Read text from clipboard
const text = await navigator.clipboard.readText();
console.log('Clipboard content:', text);
Try it:
Clipboard API Features
Text Operations
Copy and paste plain text
await navigator.clipboard.writeText(text);
const text = await navigator.clipboard.readText();
Rich Content
Handle images and formatted content
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': blob })
]);
Secure Access
Requires user permission and HTTPS
// Requires user gesture
button.onclick = async () => {
await navigator.clipboard.writeText(text);
};
Promise-based
Modern async/await syntax
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('Failed to copy');
}
🔹 Basic Text Operations
Here's how to copy and paste text using the Clipboard API:
// Copy text to clipboard
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy text: ', err);
// Fallback for older browsers
fallbackCopyTextToClipboard(text);
}
}
// Read text from clipboard
async function readFromClipboard() {
try {
const text = await navigator.clipboard.readText();
console.log('Pasted content: ', text);
return text;
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
}
}
// Fallback for older browsers
function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
console.log('Fallback: Text copied to clipboard');
} catch (err) {
console.error('Fallback: Unable to copy', err);
}
document.body.removeChild(textArea);
}
Try Different Text Operations:
🔹 Copy Code Snippets
A practical example - copy code snippets with a click:
<!-- HTML -->
<div class="code-block">
<pre><code id="code-snippet">
function greet(name) {
return `Hello, ${name}!`;
}
</code></pre>
<button onclick="copyCode()">Copy Code</button>
</div>
// JavaScript
async function copyCode() {
const codeElement = document.getElementById('code-snippet');
const code = codeElement.textContent;
try {
await navigator.clipboard.writeText(code);
showCopyFeedback('Code copied!');
} catch (err) {
showCopyFeedback('Failed to copy code', 'error');
}
}
function showCopyFeedback(message, type = 'success') {
const feedback = document.createElement('div');
feedback.textContent = message;
feedback.className = `copy-feedback ${type}`;
document.body.appendChild(feedback);
setTimeout(() => {
document.body.removeChild(feedback);
}, 2000);
}
Try it:
function calculateSum(a, b) {
return a + b;
}
const result = calculateSum(5, 3);
console.log(result); // Output: 8
🔹 Permission and Error Handling
The Clipboard API requires proper permission handling:
// Check clipboard permissions
async function checkClipboardPermission() {
try {
const permission = await navigator.permissions.query({ name: 'clipboard-read' });
console.log('Clipboard permission:', permission.state);
return permission.state === 'granted';
} catch (err) {
console.log('Permissions API not supported');
return false;
}
}
// Robust clipboard operations with error handling
async function robustClipboardWrite(text) {
// Check if Clipboard API is supported
if (!navigator.clipboard) {
console.log('Clipboard API not supported');
fallbackCopyTextToClipboard(text);
return;
}
try {
await navigator.clipboard.writeText(text);
showNotification('Copied to clipboard!', 'success');
} catch (err) {
console.error('Clipboard write failed:', err);
if (err.name === 'NotAllowedError') {
showNotification('Clipboard access denied', 'error');
} else {
showNotification('Copy failed, trying fallback...', 'warning');
fallbackCopyTextToClipboard(text);
}
}
}