← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Clipboard API

javascript HTML5 Beginner

TL;DR

The async Clipboard API (navigator.clipboard) is the modern replacement for document.execCommand('copy') — supports text, images, and rich content with proper permission handling.

Explanation

navigator.clipboard.writeText(text) and navigator.clipboard.readText() are Promise-based. For rich content: clipboard.write([new ClipboardItem({'text/html': blob})]).Read requires user permission (clipboard-read) and is only available in focused pages. Write usually doesn't require permission if triggered by user action. The old document.execCommand('copy') is deprecated — it only works synchronously and only with text. Security: clipboard access is restricted to secure contexts (HTTPS) and requires user gesture for write in some browsers.

Common Misconception

navigator.clipboard.writeText() works everywhere without permissions — it requires HTTPS (secure context) and a user gesture in some browsers.

Why It Matters

The async Clipboard API enables rich clipboard operations (images, HTML) that were impossible with the legacy execCommand approach.

Common Mistakes

  • Using document.execCommand('copy') — deprecated and unreliable across browsers.
  • Not wrapping clipboard operations in try/catch — permission denied throws.
  • Calling readText() without user interaction — blocked by browsers.

Code Examples

✗ Vulnerable
// Deprecated approach:
document.execCommand('copy'); // Deprecated, unreliable
✓ Fixed
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        showToast('Copied!');
    } catch (err) {
        // Fallback for older browsers:
        const el = document.createElement('textarea');
        el.value = text;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
    }
}

Added 23 Mar 2026
Edited 5 Apr 2026
Views 24
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 1 ping T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Perplexity 6 Amazonbot 6 Unknown AI 4 Google 2 ChatGPT 1 Majestic 1 Meta AI 1 Ahrefs 1
crawler 20 pre-tracking 2
DEV INTEL Tools & Severity
🔵 Info ⚙ Fix effort: Low
⚡ Quick Fix
Replace document.execCommand('copy') with await navigator.clipboard.writeText(text). Always wrap in try/catch and provide a fallback.
📦 Applies To
javascript HTML5 web
🔗 Prerequisites
🔍 Detection Hints
execCommand\('copy'\)
Auto-detectable: ✓ Yes eslint
🤖 AI Agent
Confidence: High False Positives: Low ✓ Auto-fixable Fix: Low Context: Function

✓ schema.org compliant