Skip to content
JavaScript

Copy Text to the Clipboard with JavaScript

Copy text to the clipboard with JavaScript using navigator.clipboard.writeText, add an accessible copy button, and provide a fallback for older browsers.

Published Updated

Use navigator.clipboard.writeText() to copy text to the clipboard in modern browsers. Call it from a user action, such as a button click, and serve the page over HTTPS:

const button = document.querySelector('#copy-button');

button.addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText('Text to copy');
    button.textContent = 'Copied!';
  } catch (error) {
    console.error('Could not copy text:', error);
  }
});

A complete copy-text button

The button below copies text from a nearby element and announces the result to assistive technology.

<pre id="code-to-copy"><code>npm install example-package</code></pre>
<button id="copy-button" type="button" aria-describedby="copy-status">
  Copy command
</button>
<span id="copy-status" role="status" aria-live="polite"></span>

<script>
  const button = document.querySelector('#copy-button');
  const source = document.querySelector('#code-to-copy');
  const status = document.querySelector('#copy-status');

  button.addEventListener('click', async () => {
    const textToCopy = source.textContent.trim();

    try {
      await navigator.clipboard.writeText(textToCopy);
      status.textContent = 'Copied to clipboard';
    } catch (error) {
      status.textContent = 'Copy failed';
      console.error(error);
    }
  });
</script>

Use textContent when the visible plain text is what you want to copy. For a form field, read its value instead:

const textToCopy = document.querySelector('#message').value;
await navigator.clipboard.writeText(textToCopy);

Why clipboard copying can fail

The Clipboard API has security requirements:

Always catch the rejected promise and show a useful message instead of assuming that the copy succeeded.

Fallback for older browsers

document.execCommand('copy') is deprecated, but a temporary textarea can still be a reasonable fallback for older browsers. The command copies the current selection; passing the desired text as a third argument does not copy that argument.

function legacyCopyText(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.setAttribute('readonly', '');
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();

  const copied = document.execCommand('copy');
  textarea.remove();
  return copied;
}

You can wrap the modern and legacy approaches in one helper:

async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    await navigator.clipboard.writeText(text);
    return true;
  }

  return legacyCopyText(text);
}

Copy rich text or an image

writeText() handles plain text. To copy HTML, images, or another MIME type, use navigator.clipboard.write() with a ClipboardItem where supported:

const html = '<strong>Copied text</strong>';
const item = new ClipboardItem({
  'text/html': new Blob([html], { type: 'text/html' }),
  'text/plain': new Blob(['Copied text'], { type: 'text/plain' }),
});

await navigator.clipboard.write([item]);

Frequently asked questions

Can JavaScript copy text without a click?

Browsers commonly require recent user activation for clipboard writes. Trigger copying directly from a click or keyboard handler rather than from a timer or page-load event.

Should I use a clipboard library?

For plain text, the native Clipboard API and a small fallback are usually enough. A library can still help when an application needs consistent legacy-browser behavior or more complex UI state.

Is navigator.clipboard.setClipboardData() valid?

No. The modern methods are navigator.clipboard.writeText() for plain text and navigator.clipboard.write() for clipboard items. Older Internet Explorer code used window.clipboardData.setData(), which should not be used for modern web applications.

Summary

Use navigator.clipboard.writeText(textToCopy) inside a user-triggered event, handle permission errors, and provide visible status feedback. Only add the deprecated selection-based fallback if supporting older browsers is a real requirement.

text to copycopy text JavaScriptJavaScript clipboardnavigator.clipboard.writeTextcopy buttonClipboard API