Rich Clipboard Architecture in React: Async Clipboard API, ClipboardItem Payloads, and Paste Sanitization
Copy and paste are among the most fundamental interactions in productivity software, yet most React applications stop at navigator.clipboard.writeText(). While writeText() is sufficient for copying an API key or share link, modern web applications—rich text editors, design canvases, data tables, and developer dashboards—require far richer clipboard semantics.
Users expect to copy a formatted table and paste it cleanly into Google Docs or Notion, copy a chart canvas directly as a PNG image, or paste a screenshot from their OS clipboard into a React dropzone without opening a file picker.
The standardized Clipboard API replaces the legacy, synchronous document.execCommand() with promise-based access to multi-format system clipboards via ClipboardItem, Clipboard.write(), and Clipboard.read().
However, implementing rich clipboard workflows in React comes with notorious cross-browser pitfalls:
- WebKit / Safari User-Gesture Expiry: If your click handler
awaits an API call orcanvas.toBlob()before callingnavigator.clipboard.write(), Safari revokes the transient user activation and throwsNotAllowedError. - Multi-Representation Fallbacks: Pasting into Slack vs. a plain-text terminal requires bundling both
text/htmlandtext/plaininside the sameClipboardItemso the target app picks the richest format it supports. - Untrusted Paste Payloads: Reading
text/htmlfrom an external paste event can introduce XSS vectors or broken inline styles unless sanitized before entering React state. - Permission Differences: Writing on an active tab is usually granted automatically, whereas
navigator.clipboard.read()triggers a browser permission prompt unless triggered via a nativeonPasteevent.
In this architectural guide, we build a production-grade clipboard system in React: constructing Safari-safe ClipboardItem promises, building a useClipboard hook, handling onPaste image and HTML extraction, and comparing Async Clipboard vs. Clipboard Events.
Multi-Representation ClipboardItem Architecture
[React Component: Copy Rich Table or Chart]
|
v
new ClipboardItem({
'text/html': Promise<Blob> ---> Rich editors (Notion, Docs, Email)
'text/plain': Promise<Blob> ---> Code editors, terminals, plain inputs
'web app/json': Promise<Blob> --> Custom format (same-app lossless paste)
})
|
v
navigator.clipboard.write([item]) <-- Invoked synchronously on click!
Why Deferred Promise<Blob> Values Matter
According to the ClipboardItem specification, each MIME-type value can be either a Blob or a Promise<Blob>. Passing a Promise<Blob> lets you call navigator.clipboard.write() synchronously inside the onClick call stack, preserving Safari's strict user-activation token while your app asynchronously fetches data or renders a canvas to PNG.
Building a Safari-Safe useClipboard Hook
Here is a strictly typed React hook that handles plain text, multi-format rich text (text/html + text/plain), binary PNG exports, and automatic "Copied!" feedback timers with cleanup:
// hooks/useClipboard.ts
import { useState, useCallback, useRef, useEffect } from 'react';
export type CopyStatus = 'idle' | 'copied' | 'error';
interface UseClipboardOptions {
resetDelayMs?: number;
}
export function useClipboard({ resetDelayMs = 2000 }: UseClipboardOptions = {}) {
const [status, setStatus] = useState<CopyStatus>('idle');
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const timerRef = useRef<number | null>(null);
const clearTimer = useCallback(() => {
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
timerRef.current = null;
}
}, []);
useEffect(() => clearTimer, [clearTimer]);
const scheduleReset = useCallback(() => {
clearTimer();
timerRef.current = window.setTimeout(() => {
setStatus('idle');
}, resetDelayMs);
}, [clearTimer, resetDelayMs]);
/**
* Copy plain text with graceful fallback.
*/
const copyText = useCallback(
async (text: string): Promise<boolean> => {
setErrorMessage(null);
try {
await navigator.clipboard.writeText(text);
setStatus('copied');
scheduleReset();
return true;
} catch (err) {
setStatus('error');
setErrorMessage(err instanceof Error ? err.message : 'Clipboard write failed');
return false;
}
},
[scheduleReset]
);
/**
* Copy both HTML and plain text simultaneously.
* Accepts async factories so navigator.clipboard.write() runs within the user gesture.
*/
const copyRichContent = useCallback(
async (
getHtml: () => Promise<string> | string,
getPlainText: () => Promise<string> | string
): Promise<boolean> => {
setErrorMessage(null);
try {
if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) {
const fallbackText = await getPlainText();
return copyText(fallbackText);
}
const item = new ClipboardItem({
'text/html': Promise.resolve(getHtml()).then(
(html) => new Blob([html], { type: 'text/html' })
),
'text/plain': Promise.resolve(getPlainText()).then(
(text) => new Blob([text], { type: 'text/plain' })
),
});
await navigator.clipboard.write([item]);
setStatus('copied');
scheduleReset();
return true;
} catch (err) {
setStatus('error');
setErrorMessage(err instanceof Error ? err.message : 'Rich copy failed');
return false;
}
},
[copyText, scheduleReset]
);
/**
* Copy a PNG Blob (e.g., from a <canvas>) while preserving Safari user activation.
*/
const copyImage = useCallback(
async (getPngBlob: () => Promise<Blob>): Promise<boolean> => {
setErrorMessage(null);
try {
if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) {
throw new Error('Image clipboard writing is not supported in this browser.');
}
const item = new ClipboardItem({
'image/png': getPngBlob(),
});
await navigator.clipboard.write([item]);
setStatus('copied');
scheduleReset();
return true;
} catch (err) {
setStatus('error');
setErrorMessage(err instanceof Error ? err.message : 'Image copy failed');
return false;
}
},
[scheduleReset]
);
return {
status,
errorMessage,
copyText,
copyRichContent,
copyImage,
};
}
Handling onPaste Safely in React
When users press Cmd+V / Ctrl+V inside your app, React's synthetic onPaste event (React.ClipboardEvent) gives you synchronous access to event.clipboardData without triggering a browser permission prompt.
Before rendering pasted HTML or storing it in state, strip dangerous tags (<script>, <iframe>, on* event attributes) using a sanitizer helper, and extract pasted image files cleanly:
// utils/pasteParser.ts
export interface ParsedPasteResult {
plainText: string;
sanitizedHtml: string | null;
images: File[];
}
/**
* Minimal allow-list HTML sanitizer for pasted fragments.
* In production, pair with DOMPurify for comprehensive XSS defense.
*/
export function sanitizePastedHtml(rawHtml: string): string {
const parser = new DOMParser();
const doc = parser.parseFromString(rawHtml, 'text/html');
const blockedTags = doc.querySelectorAll('script, style, iframe, object, embed');
blockedTags.forEach((node) => node.remove());
const allElements = doc.body.querySelectorAll('*');
allElements.forEach((el) => {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase();
if (name.startsWith('on') || attr.value.trim().toLowerCase().startsWith('javascript:')) {
el.removeAttribute(attr.name);
}
}
});
return doc.body.innerHTML;
}
export function parseReactPasteEvent(
event: React.ClipboardEvent<HTMLElement>
): ParsedPasteResult {
const { clipboardData } = event;
const plainText = clipboardData.getData('text/plain');
const rawHtml = clipboardData.getData('text/html');
const images: File[] = [];
for (const item of Array.from(clipboardData.items)) {
if (item.kind === 'file' && item.type.startsWith('image/')) {
const file = item.getAsFile();
if (file) images.push(file);
}
}
return {
plainText,
sanitizedHtml: rawHtml ? sanitizePastedHtml(rawHtml) : null,
images,
};
}
Production Component: Rich Table Copy & Paste Dropzone
Here is a complete React component demonstrating:
- Copying a styled HTML table plus tab-separated plain text in one
ClipboardItem. - Reading clipboard contents via
navigator.clipboard.read()on button click, or viaonPastewithout prompts. - Previewing pasted images safely with
URL.createObjectURLcleanup.
// components/RichClipboardWorkbench.tsx
import React, { useState, useEffect } from 'react';
import { useClipboard } from '../hooks/useClipboard';
import { parseReactPasteEvent } from '../utils/pasteParser';
const SAMPLE_ROWS = [
{ service: 'api-gateway', p95: '18ms', status: 'Healthy' },
{ service: 'auth-worker', p95: '11ms', status: 'Healthy' },
{ service: 'pdf-renderer', p95: '142ms', status: 'Degraded' },
];
export function RichClipboardWorkbench() {
const { status, errorMessage, copyRichContent } = useClipboard();
const [pastedText, setPastedText] = useState<string>('');
const [pastedImageUrl, setPastedImageUrl] = useState<string | null>(null);
useEffect(() => {
return () => {
if (pastedImageUrl) URL.revokeObjectURL(pastedImageUrl);
};
}, [pastedImageUrl]);
const handleCopyTable = () => {
const buildHtml = () => {
const rows = SAMPLE_ROWS.map(
(r) => `<tr><td>${r.service}</td><td>${r.p95}</td><td>${r.status}</td></tr>`
).join('');
return `<table><thead><tr><th>Service</th><th>P95</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>`;
};
const buildTsv = () => {
const header = 'Service\tP95\tStatus';
const body = SAMPLE_ROWS.map((r) => `${r.service}\t${r.p95}\t${r.status}`).join('
');
return `${header}
${body}`;
};
copyRichContent(buildHtml, buildTsv);
};
const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
const parsed = parseReactPasteEvent(e);
if (parsed.images.length > 0) {
e.preventDefault();
if (pastedImageUrl) URL.revokeObjectURL(pastedImageUrl);
setPastedImageUrl(URL.createObjectURL(parsed.images[0]));
setPastedText(`Pasted image: ${parsed.images[0].name || 'clipboard.png'}`);
return;
}
if (parsed.plainText) {
setPastedText(parsed.plainText);
}
};
return (
<div className="max-w-2xl mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl space-y-5">
<div className="flex items-center justify-between border-b border-slate-800 pb-4">
<div>
<h2 className="text-lg font-bold text-white">Rich Clipboard Workbench</h2>
<p className="text-xs text-slate-400">
Copies HTML table + TSV plain text simultaneously via ClipboardItem.
</p>
</div>
<button
onClick={handleCopyTable}
className="px-4 py-2 text-xs font-semibold rounded-lg bg-sky-500 hover:bg-sky-600 text-white transition"
>
{status === 'copied' ? 'Copied Table!' : 'Copy Rich Table'}
</button>
</div>
{errorMessage && (
<div className="p-3 rounded-lg bg-rose-950/60 border border-rose-800 text-xs text-rose-300">
{errorMessage}
</div>
)}
<div
onPaste={handlePaste}
tabIndex={0}
className="p-6 rounded-xl bg-slate-950 border-2 border-dashed border-slate-700 focus:border-sky-500 focus:outline-none text-center space-y-3 cursor-text"
>
<p className="text-xs text-slate-400">
Click here and press <kbd className="px-1.5 py-0.5 bg-slate-800 rounded text-slate-200">Cmd/Ctrl+V</kbd> to paste text, HTML, or a screenshot.
</p>
{pastedImageUrl && (
<img
src={pastedImageUrl}
alt="Pasted preview"
className="max-h-48 mx-auto rounded-lg border border-slate-800"
/>
)}
{pastedText && (
<pre className="text-left text-xs font-mono text-emerald-400 bg-slate-900 p-3 rounded-lg overflow-x-auto">
{pastedText}
</pre>
)}
</div>
</div>
);
}
Architectural Comparison & Trade-Offs
| Mechanism | navigator.clipboard.writeText() | navigator.clipboard.write([ClipboardItem]) | React onPaste (ClipboardEvent) |
|---|---|---|---|
| Supported Formats | Plain text only | text/plain, text/html, image/png, custom web | Text, HTML, and pasted File objects |
| Permission Prompt | Usually silent on active tab | Silent on active tab (user gesture required) | Never prompts (user initiated Cmd/Ctrl+V) |
| Async Data Support | Must await string first | Supports Promise<Blob> to keep Safari gesture | Synchronous access during event dispatch |
| Ideal Use Case | Share links, code snippets | Rich tables, canvas PNGs, multi-format copy | Image dropzones, rich editor paste |
Key Production Best Practices
- Always Check
ClipboardItem.supports()for Optional MIME Types: Browsers are required to supporttext/plain,text/html, andimage/png. Before writingimage/svg+xmlor customwebformats, verify support withClipboardItem.supports(mimeType). - Never Await Before Calling
clipboard.write(): Wrap async work insidePromise<Blob>values passed tonew ClipboardItem(...)so the write call executes in the synchronous tick of the user's click. - Revoke Object URLs for Pasted Images: Always clean up
URL.createObjectURL(file)in auseEffectteardown to avoid memory leaks when users paste multiple screenshots.
Conclusion
The modern Clipboard API elevates copy-and-paste in React from fragile plain-text workarounds to rich, multi-format desktop parity. By passing Promise<Blob> values into ClipboardItem to satisfy Safari's gesture rules, sanitizing external HTML on onPaste, and pairing rich representations with plain-text fallbacks, your React app can support seamless workflows across every browser and target application.