Script Valley
JavaScript in the Browser: DOM, Events & APIs
Web APIs: History, URL, Clipboard, and ObserversLesson 6.3

Clipboard API: reading and writing text in the browser

navigator.clipboard.writeText, readText, clipboard permissions, async clipboard, fallback execCommand, copy event, paste event

Clipboard API

The modern Clipboard API is asynchronous and permission-based. It works over HTTPS only.

// Copy text to clipboard
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    showToast('Copied!');
  } catch (err) {
    console.error('Copy failed:', err);
  }
}

// Read text from clipboard
async function pasteFromClipboard() {
  try {
    const text = await navigator.clipboard.readText();
    document.querySelector('#input').value = text;
  } catch (err) {
    console.error('Paste denied:', err);
  }
}

Copy Button Pattern

document.querySelectorAll('[data-copy]').forEach(btn => {
  btn.addEventListener('click', () => {
    const target = document.querySelector(btn.dataset.copy);
    copyToClipboard(target.textContent);
    btn.textContent = 'Copied ✓';
    setTimeout(() => btn.textContent = 'Copy', 2000);
  });
});

Clipboard Events

Listen to copy, cut, and paste events on elements or document to intercept or modify clipboard actions. The paste event gives access to e.clipboardData.

document.addEventListener('paste', (e) => {
  const text = e.clipboardData.getData('text/plain');
  console.log('Pasted:', text);
});

Up next

MutationObserver: watching DOM changes without polling

Sign in to track progress