Copy Text to Clipboard
Copies text to the user's clipboard using modern clipboard APIs when available, falling back to older methods for browser compatibility. Returns a Promise that resolves when the operation completes.
Import
import { copyToClipboard } from 'nhb-toolbox';
Function Signature
async function copyToClipboard(text: string): Promise<void>
Usage Examples
- Basic
- With UI Button
- With Error Logging
await copyToClipboard('Hello, world!');
// The text "Hello, world!" is now in the clipboard.
<button onClick={() => copyToClipboard('Copied!')}>
Copy
</button>
await copyToClipboard('May fail in unsupported browsers');
// Logs an error with throwing it again if copy fails.
API Reference
Parameters
Name | Type | Description |
---|---|---|
text | string | The text to copy. |
Returns
A Promise that resolves once the text is successfully copied, or after a fallback attempt.
Key Features
- Universal Support: Uses
navigator.clipboard.writeText
if available, else falls back to legacy method. - Promise-based: Can be awaited, useful in modern async workflows (click handlers, etc).
- Error Handling: Logs error to console if copying fails, with throwing the error.
Limitations
- Browser-only: Not available in Node.js or non-browser environments.
- User Permissions: Clipboard access may require user action or browser permissions.
Notes
- Works without page reload or user prompt in supported browsers.
- May fail in rare cases if used in insecure (non-https) contexts or inside some browser iframes.
- For full support, ensure the function is triggered as a result of user interaction (e.g., button click).
- On legacy/unsupported browsers, falls back to creating a hidden
<textarea>
.
Recommended Use Cases
- "Copy" buttons for code samples, passwords, or referral links.
- Improving UX with easy clipboard access.
- Copy-to-clipboard in dashboards, editors, or utilities.
Conclusion:
copyToClipboard
is a reliable, browser-focused solution for programmatic copying, handling compatibility quirks under the hood. Integrate it for pain-free copy actions—users appreciate simple clipboard access!