Recipe 14.5

Copying and Pasting Text

You can use the Clipboard API to read text from, and write text to, the system clipboard. This lets you add copy and paste functionality to your apps.

Demo

Code

JavaScript
const textarea = document.querySelector('#text-area');
const copyButton = document.querySelector('#copy-button');
const pasteButton = document.querySelector('#paste-button');

copyButton.addEventListener('click', async () => {
  const { selectionStart, selectionEnd } = textarea;
  const selectedText = textarea.value.slice(selectionStart, selectionEnd);

  try {
    await navigator.clipboard.writeText(selectedText);
  } catch (error) {
    console.error('Clipboard error:', error);
  }
});

pasteButton.addEventListener('click', async () => {
  const currentValue = textarea.value;
  const { selectionStart, selectionEnd } = textarea;

  try {
    const clipboardValue = await navigator.clipboard.readText();
    const newValue = currentValue.slice(0, selectionStart) + clipboardValue + currentValue.slice(selectionEnd);
    textarea.value = newValue;
  } catch (error) {
    console.error('Clipboard error:', error);
  }
});
HTML
<div class="mb-4">
  <button type="button" id="copy-button" class="btn btn-secondary">Copy</button>
  <button type="button" id="paste-button" class="btn btn-secondary">Paste</button>
</div>
<textarea placeholder="Enter some text..." id="text-area" class="my-4 form-control"></textarea>
Web API Cookbook
Joe Attardi