How to Copy Text to Clipboard in JavaScript Easily
Use the
navigator.clipboard.writeText() method to copy text to the clipboard in JavaScript. This method is asynchronous and works in modern browsers with user permission.Syntax
The basic syntax to copy text to clipboard is:
navigator.clipboard.writeText(text): Copies thetextstring to the clipboard.- This method returns a
Promisethat resolves when the text is copied successfully. - It requires the page to be served over HTTPS and user interaction (like a button click) to work.
javascript
navigator.clipboard.writeText('Your text here') .then(() => console.log('Text copied!')) .catch(err => console.error('Failed to copy text:', err));
Output
Text copied!
Example
This example shows a button that copies a fixed text to the clipboard when clicked and logs success or failure in the console.
javascript
const copyButton = document.createElement('button'); copyButton.textContent = 'Copy Text'; document.body.appendChild(copyButton); copyButton.addEventListener('click', () => { navigator.clipboard.writeText('Hello, clipboard!') .then(() => console.log('Text copied!')) .catch(err => console.error('Failed to copy text:', err)); });
Output
Text copied!
Common Pitfalls
- Trying to copy text without user interaction (like on page load) will usually fail due to browser security.
- Using deprecated methods like
document.execCommand('copy')is less reliable and not recommended. - Clipboard API requires HTTPS; it won't work on insecure HTTP pages.
- Always handle the
Promiseto catch errors and inform users if copying fails.
javascript
/* Wrong way: copying without user action (likely to fail) */ navigator.clipboard.writeText('No user click') .then(() => console.log('Copied')) .catch(() => console.log('Failed')); /* Right way: copy inside a user event handler */ document.querySelector('button').addEventListener('click', () => { navigator.clipboard.writeText('User clicked') .then(() => console.log('Copied')) .catch(() => console.log('Failed')); });
Quick Reference
Summary tips for copying text to clipboard in JavaScript:
- Use
navigator.clipboard.writeText()inside user-triggered events. - Handle success and failure with
thenandcatch. - Ensure your site uses HTTPS for Clipboard API support.
- Avoid deprecated methods like
document.execCommand('copy').
Key Takeaways
Use navigator.clipboard.writeText() inside user interaction events to copy text safely.
Always handle the Promise returned to catch errors and confirm success.
Clipboard API requires HTTPS and user permission to work.
Avoid deprecated methods like document.execCommand('copy') for better reliability.