How to Copy Text to the Clipboard with JavaScript
Learn to enhance web apps with Clipboard API. Copy text easily, check permissions, and create interactive features.
Yogini Bende
Sep 12, 2024 • 3 min read
We see "Copy Link" options almost across all the apps these days. In modern web development, integrating clipboard features can is an important part of improving user interaction. This functionality is particularly useful for copying activation codes, recovery keys, or code snippets with a single click, eliminating the need for manual text selection and keyboard shortcuts.
The Evolution of Clipboard Interaction
Historically, developers relied on the document.execCommand()
method for clipboard operations. However, this approach has been deprecated. Enter the Clipboard API - a more robust and future-proof solution for managing clipboard actions asynchronously.
Quick Implementation Guide
If you are here looking for a quick solution, here's a concise code snippet:
export const ClipboardExample = () => {
const copyContent = async () => {
const text = document.getElementById('copyTarget').textContent;
try {
await navigator.clipboard.writeText(text);
console.log('Content successfully copied');
} catch (error) {
console.error('Copy operation failed:', error);
}
};
return (
<>
<p id='copyTarget'>Sample text for clipboard</p>
<button onClick={copyContent}>Copy Text</button>
</>
);
};
Understanding Clipboard API Permissions
Before implementing clipboard functionality, it's crucial to verify browser support and permissions:
export const CheckClipboardPermissions = () => {
const checkPermissions = async () => {
try {
const result = await navigator.permissions.query({
name: 'clipboard-write',
});
if (result.state === 'granted' || result.state === 'prompt') {
alert('Clipboard write access is available');
} else {
alert('Clipboard write access is restricted');
}
} catch (error) {
console.error('Permission check failed:', error);
}
};
return (
<button onClick={checkPermissions}>Check Clipboard Permissions</button>
);
};
Implementing Text Copying
The Clipboard API's writeText()
method provides an asynchronous way to copy text:
export const CopyTextExample = () => {
const copyText = async (text) => {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied successfully');
} catch (error) {
console.error('Copy failed:', error);
}
};
return (
<button onClick={() => copyText('Example text to copy')}>
Copy to Clipboard
</button>
);
};
Practical Application: Quote Copier
Let's create a more complex example that fetches quotes from an API and allows users to copy them:
import { useState, useEffect } from 'react';
export const QuoteCopier = () => {
const [quote, setQuote] = useState({ text: '', author: '' });
const [isCopied, setIsCopied] = useState(false);
useEffect(() => {
fetchQuote();
}, []);
const fetchQuote = async () => {
try {
const response = await fetch(
'https://thesimpsonsquoteapi.glitch.me/quotes'
);
const data = await response.json();
setQuote({ text: data.quote, author: data.character });
} catch (error) {
console.error('Failed to fetch quote:', error);
}
};
const copyQuote = async () => {
try {
await navigator.clipboard.writeText(`"${quote.text}" - ${quote.author}`);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (error) {
console.error('Failed to copy quote:', error);
}
};
return (
<div>
<blockquote>{quote.text}</blockquote>
<p>- {quote.author}</p>
<button onClick={copyQuote}>{isCopied ? 'Copied!' : 'Copy Quote'}</button>
<button onClick={fetchQuote}>New Quote</button>
</div>
);
};
This example demonstrates how to integrate API calls with clipboard functionality, providing a dynamic and interactive user experience.
Remember, the Clipboard API is designed for secure contexts, typically requiring HTTPS. Always handle potential errors and provide user feedback for a smooth experience.
By leveraging the Clipboard API, you can create more intuitive and user-friendly web applications, enhancing overall usability and satisfaction.
And, if you are looking for JavaScript Jobs, you are at a right place. You can apply to frontend developer jobs on Peerlist Jobs.