Browser APIs & Web APIs
Clipboard API
Master modern clipboard interactions in JavaScript. Learn to read and write text asynchronously using navigator.clipboard, request permissions, and handle clipboard events.
1. Introduction
Copying and pasting text is a common user action. Historically, this was handled using the synchronous document.execCommand('copy') API. Modern browsers provide the asynchronous Clipboard API for more secure and flexible clipboard operations.
2. Why It Matters
The legacy execCommand API is deprecated and has security issues because it runs synchronously on the main thread and lacks permissions controls. The new Clipboard API is asynchronous and requires user permission before reading from the clipboard, which helps protect user data.
3. Real-World Analogy
Think of a Public Clipboard File in a Shared Office:
- Legacy execCommand (Insecure Desk): Leaving your document open on a desk. Anyone walking by can write on the paper or read your notes without permission (highly insecure).
- Modern Clipboard API (Secure Office Box): A locked box managed by an assistant. If you want to place a document in the box (copy to clipboard), you hand it to the assistant. If you want to read what is inside the box (paste from clipboard), the assistant stops you and asks: "Do you have permission to read this data?" (Permissions prompt).
4. The Clipboard API
The Clipboard API is accessed via the navigator.clipboard object:
1. Writing to the Clipboard (Copy):
Call navigator.clipboard.writeText(text). This returns a Promise that resolves when the text is successfully copied to the clipboard.
2. Reading from the Clipboard (Paste):
Call navigator.clipboard.readText(). This returns a Promise that resolves to the text content currently on the clipboard. This operation requires permission.
5. Practical Example
This script demonstrates implementing a "Copy to Clipboard" button helper:
6. Common Mistakes
- Trying to run Clipboard API outside secure contexts: Like Geolocation, the Clipboard API is a powerful feature that requires a secure context. It is disabled on non-secure (HTTP) connections, except on
localhost. - Attempting to read clipboard data without user interaction: To prevent scripts from silently reading user clipboard data, browsers restrict clipboard read operations to code that runs inside user interaction handlers (like a click event). Calling
readText()on page load throws a SecurityError.
7. Quick Quiz
Q1: Which method should you use to copy text to the clipboard asynchronously?
A) navigator.clipboard.readText()
B) navigator.clipboard.writeText()
Answer: B — navigator.clipboard.writeText() writes text content to the system clipboard asynchronously.
8. Scenario-Based Challenge
The Encapsulated Rich Text Paste Processor:
You want to write a rich text editor. When a user pastes data, parse both text/plain format and text/html format from the clipboard. Write the event listener that monitors the window paste event and extracts both data types.
9. Debugging Exercise
Explain why this clipboard paste operation fails, and how to fix it:
// Objective: read clipboard data when script runs
async function getSharedToken() {
const token = await navigator.clipboard.readText(); // Throws SecurityError! Why?
console.log(token);
}
getSharedToken();
View Solution
Diagnosis: Browsers block clipboard read operations unless they are triggered directly by user interaction (like clicking a button) to prevent websites from silently stealing data from the user's clipboard.
Fix: Trigger the clipboard read operation inside a user click event listener:
const pasteBtn = document.getElementById('paste-btn');
pasteBtn.addEventListener('click', async () => { try { const token = await navigator.clipboard.readText(); // Works inside event handler! console.log(token); } catch (err) { console.error('Failed to read:', err.message); } });
10. Interview Questions
🟢 Q1: Compare the legacy document.execCommand('copy') with the modern Clipboard API.
Answer:
• Execution Type: document.execCommand() is synchronous and runs on the main execution thread, which can block rendering. The Clipboard API is asynchronous and returns a Promise, preventing UI blocks.
• Permissions: execCommand() lacks permission controls, allowing scripts to write to the clipboard silently. The Clipboard API uses the Permissions API to request access explicitly before reading clipboard data.
• Support: execCommand() is deprecated in modern browsers. The Clipboard API is the standard for modern web development.
11. Production Considerations
- • Clipboard Fallback Pattern: While the Clipboard API is widely supported, some older browsers may not support it. Implement a fallback to the legacy
document.execCommand()API for compatibility when building copy buttons in production.