Explain Codes LogoExplain Codes Logo

How do I copy to the clipboard in JavaScript?

javascript
prompt-engineering
clipboard-api
copying-text
Nikita BarsukovbyNikita Barsukov·Feb 12, 2025
TLDR

The standard practice to copy text in JavaScript involves the navigator.clipboard.writeText(text) method. Execution of this method should occur during an event like onclick:

button.addEventListener('click', () => { // We are now stepping into a world where we can manipulate the clipboard! const text = 'Text to copy'; navigator.clipboard.writeText(text) .then(() => console.log('Copied to clipboard!')) .catch(err => console.error('Too bad, copying failed', err)); });

Remember, this only works within user-initiated events due to security reasons.

Step-by-step breakdown

  1. User actions activation: Pasting to the clipboard necessitates user actions such as clicks or keypresses to satisfy current web security standards.

  2. Using navigator.clipboard.writeText: This asynchronous function is the optimal choice for copying plain text. It's worth noting that this must be used in a secure context—most modern browsers support this method if served over HTTPS. Do keep in mind to avoid it being blocked on the main thread.

  3. Fallback approach — document.execCommand('copy'): When navigator.clipboard isn't available (perhaps on older browsers or HTTP sites), consider using the crusty, but reliable document.execCommand('copy'). This method is deprecated, and can behave sporadically—use with care!

function fallbackCopyTextToClipboard(text) { const textArea = document.createElement("textarea"); textArea.value = text; // We're about to force Edge to behave. textArea.style.position = 'fixed'; document.body.appendChild(textArea); textArea.focus(); textArea.select(); // You could throw an exception—even if you're not exceptional. try { const copyingSuccess = document.execCommand('copy'); const successMessage = copyingSuccess ? 'successful' : 'unsuccessful'; console.log(`Fallback: The text was ${successMessage} copied`); } catch (err) { console.error('Fallback: Too bad we couldn’t copy', err); } // Uh-oh cleanup time document.body.removeChild(textArea); }

Tackling the unknowns — Edge and IE

From the frontline of cross-browser compatibility, comes our next move. Dealing with Internet Explorer (IE) requires addressing its idiosyncrasies—like invoking the createTextRange method:

const textRange = document.body.createTextRange(); textRange.moveToElementText(document.getElementById('content')); textRange.select().createTextRange(); document.execCommand("copy");

In the realm of Microsoft Edge, to prevent a sudden leap to the bottom when a hidden textarea is focused, you can outsmart it by shoving its position off-screen:

textArea.style.top = 0; textArea.style.left = '-9999px'; // You go there, when things go out of bounds. textArea.style.position = 'absolute';

Lastly, proactively checking feature availability with document.queryCommandSupported('copy') helps confirm your copying superpowers before embarking on the operation.

Advanced clipboard — copying rich content

When you want to impress your date by coping more than just plain text—maybe a multilayered rich text or images, your sure-shot trick is to follow the broad instructions outlined in the Clipboard API's copy event:

document.addEventListener('copy', (event) => { const clipboardData = event.clipboardData || window.clipboardData; // Presto! Content is flown from document to clipboard! clipboardData.setData('text/plain', 'Text to be copied'); // If you tell the default action to buzz off, it listens event.preventDefault(); });

Remember, manual handling of events and DataTransfer objects would need more knowledge under the hood. But hey, the control you gain is absolute!

User interface - Putting 'em in control

Make all your clipboard instructions user-centric. The user should captain the ship—initiating the copy action in most cases, preferably via a dedicated button or link. Throw in a confirmation of a successful copying to reassure your users:

function copyToClipboard(text) { if (!navigator.clipboard) { window.prompt('Copy to clipboard: Ctrl+C, Enter', text); return; } // I hate to say it, but you gotta handle your errors navigator.clipboard.writeText(text).catch(err => { // No worries, this is old school copying for a tougher world window.prompt('Copy to clipboard: Ctrl+C, Enter', text); console.error('Async: Could not copy text: ', err); }); }

This savvy function prompts the user to copy the text manually when the programmatic approach nose-dives, ensuring that functionality always wins over API tantrums.