Clipboard
String Manipulation
Copying Text
Programming Tips
Software Development

How do I copy a string to the clipboard?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Copying text to the clipboard is straightforward in modern browsers, but it is one of those tasks where environment rules matter. A reliable solution uses the async Clipboard API first, then falls back carefully for older browsers while keeping the user informed about success or failure.

Use the Modern Clipboard API

The preferred browser API is navigator.clipboard.writeText. It is promise-based, so you can await the result and only show success after the browser confirms the write.

html
1<button id="copy-btn">Copy code</button>
2<code id="coupon">SPRING-2026</code>
3<p id="status" aria-live="polite"></p>
4
5<script>
6  const button = document.getElementById('copy-btn');
7  const coupon = document.getElementById('coupon');
8  const status = document.getElementById('status');
9
10  button.addEventListener('click', async () => {
11    try {
12      await navigator.clipboard.writeText(coupon.textContent.trim());
13      status.textContent = 'Copied to clipboard';
14    } catch (err) {
15      status.textContent = 'Copy failed';
16      console.error(err);
17    }
18  });
19</script>

This is the cleanest option because it does not require selection hacks or hidden inputs. It also makes error handling explicit.

Wrap Copy Logic in a Small Utility

Applications usually need clipboard support in more than one place. A helper function keeps the rest of the UI code simple.

javascript
1export async function copyText(text) {
2  if (navigator.clipboard && window.isSecureContext) {
3    await navigator.clipboard.writeText(text);
4    return true;
5  }
6
7  const textarea = document.createElement('textarea');
8  textarea.value = text;
9  textarea.setAttribute('readonly', '');
10  textarea.style.position = 'fixed';
11  textarea.style.left = '-9999px';
12  document.body.appendChild(textarea);
13  textarea.select();
14
15  try {
16    return document.execCommand('copy');
17  } finally {
18    document.body.removeChild(textarea);
19  }
20}

That fallback uses document.execCommand('copy'), which is legacy but still useful when you must support older browser environments.

Example usage:

javascript
1import { copyText } from './clipboard.js';
2
3document.getElementById('copy-email').addEventListener('click', async () => {
4  const ok = await copyText('[email protected]');
5  console.log(ok ? 'copied' : 'not copied');
6});

Understand the Browser Restrictions

Clipboard write access is intentionally limited.

  • It usually requires HTTPS or localhost.
  • It should be triggered by a user gesture such as a click.
  • It may fail if permissions are denied or the tab is not in a suitable state.

That means code which works in local development can fail on a staging environment served over plain HTTP. The API is not broken in that case; the page is simply not in a trusted context.

You should also avoid surprising clipboard writes. Copying in response to a clear user action is good UX. Writing to the clipboard on page load or in a timer is usually blocked and can feel hostile even if it succeeds somewhere.

Add Good UX Around the Copy Action

The copy itself is only half the job. Users need to know whether it worked. A short visible message plus an aria-live region makes the interaction usable and accessible.

html
1<button id="copy-link">Copy share link</button>
2<span id="result" role="status" aria-live="polite"></span>
3
4<script>
5  const result = document.getElementById('result');
6
7  document.getElementById('copy-link').addEventListener('click', async () => {
8    try {
9      await navigator.clipboard.writeText('https://example.com/share/42');
10      result.textContent = 'Link copied';
11    } catch {
12      result.textContent = 'Copy failed. Please select and copy manually.';
13    }
14  });
15</script>

This prevents silent failure and gives screen-reader users the same confirmation as sighted users.

Common Pitfalls

  • Calling clipboard code outside a user gesture often causes rejection in modern browsers.
  • Testing only on localhost can hide HTTPS-related failures that appear later in staging or production.
  • Assuming the fallback always works is risky because legacy copy commands are increasingly restricted.
  • Copying raw text without trimming or formatting checks can give users an unexpected value.
  • Logging errors only to the console leaves users with no clue whether the action succeeded.

Summary

  • Prefer navigator.clipboard.writeText in modern browsers.
  • Use a small fallback utility only when older support is required.
  • Trigger copy from explicit user interaction and in a secure context.
  • Show visible and accessible success or failure feedback.
  • Normalize the string before copying so the clipboard contains exactly what the user expects.

Course illustration
Course illustration

All Rights Reserved.