Clipboard Events: copy, cut, paste
You'll learn how to intercept clipboard operations to customize what gets copied or pasted, and how to access clipboard data during these actions.
The Core Idea
When users copy, cut, or paste content in your web page, the browser fires special clipboard events. By listening to these events, you can intervene in the clipboard operation—modifying what gets placed on the clipboard, preventing the default behavior, or reading what's being pasted. This gives you control over data transfer between your page and the user's clipboard.
Think of it like having a security checkpoint at a border crossing: you can inspect what's going in or out, modify it, or block it entirely.
The Three Clipboard Events
copy– Fires when the user copies text (Ctrl+C or right-click copy)cut– Fires when the user cuts text (Ctrl+X)paste– Fires when the user pastes content (Ctrl+V)
All three events are triggered on the element that has focus or the document.
Working with ClipboardEvent
These events provide a ClipboardEvent object with a clipboardData property. You can use getData() to read clipboard content and setData() to customize what gets copied or cut:
document.addEventListener('copy', function(event) {
event.preventDefault(); // Stop default copy behavior
event.clipboardData.setData('text/plain', 'Custom copied text!');
});
document.addEventListener('paste', function(event) {
event.preventDefault();
const pastedText = event.clipboardData.getData('text/plain');
console.log('User pasted:', pastedText);
});
Common use cases include adding copyright notices to copied text, sanitizing pasted content, or preventing clipboard access in sensitive fields.
Key Takeaway: Clipboard events (copy, cut, paste) let you intercept and customize clipboard operations using event.clipboardData to read or modify the transferred data.