Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีคัดลอกข้อความไปยังคลิปบอร์ด (Clipboard) ด้วย JavaScript


ตัวอย่างโค้ด

ใช้ Clipboard API สมัยใหม่ (navigator.clipboard.writeText()) ซึ่งเป็นมาตรฐานปัจจุบัน แทน document.execCommand('copy') ที่ล้าสมัยและถูก Deprecated

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Copy to Clipboard</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
    .input-group { display: flex; gap: 10px; align-items: center; margin-bottom: 20px; }
    input[type="text"] {
      flex: 1; padding: 12px; font-size: 16px; border: 2px solid #ddd; border-radius: 4px;
    }
    button {
      padding: 12px 24px; background: #4CAF50; color: white; border: none;
      border-radius: 4px; font-size: 16px; font-weight: bold; cursor: pointer;
      transition: background 0.2s;
    }
    button:hover { background: #45a049; }
    button:disabled { background: #ccc; cursor: not-allowed; }
    .toast {
      position: fixed; bottom: 20px; right: 20px; background: #333; color: white;
      padding: 15px 25px; border-radius: 4px; display: none; z-index: 1000;
      animation: slideIn 0.3s ease;
    }
    .toast.show { display: block; }
    .toast.success { background: #4CAF50; }
    .toast.error { background: #f44336; }
    @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
  </style>
</head>
<body>
  <h1>คัดลอกข้อความไปยังคลิปบอร์ด</h1>
  
  <div class="input-group">
    <input type="text" id="textInput" value="Hello World" placeholder="พิมพ์ข้อความที่ต้องการคัดลอก" />
    <button id="copyBtn">คัดลอก</button>
  </div>
  
  <div class="input-group">
    <button id="copyStaticBtn">คัดลอกข้อความคงที่ "สวัสดีครับ"</button>
  </div>

  <div id="toast" class="toast">คัดลอกสำเร็จ!</div>

  <script>
    const textInput = document.getElementById('textInput');
    const copyBtn = document.getElementById('copyBtn');
    const copyStaticBtn = document.getElementById('copyStaticBtn');
    const toast = document.getElementById('toast');

    // ฟังก์ชันคัดลอกแบบสมัยใหม่ (Async)
    async function copyToClipboard(text) {
      try {
        await navigator.clipboard.writeText(text);
        showToast('คัดลอกสำเร็จ!', 'success');
        return true;
      } catch (err) {
        console.error('คัดลอกล้มเหลว:', err);
        showToast('คัดลอกล้มเหลว: ' + err.message, 'error');
        return false;
      }
    }

    function showToast(message, type = 'success') {
      toast.textContent = message;
      toast.className = 'toast show ' + type;
      setTimeout(() => toast.classList.remove('show'), 3000);
    }

    // Event listeners
    copyBtn.addEventListener('click', () => copyToClipboard(textInput.value));
    copyStaticBtn.addEventListener('click', () => copyToClipboard('สวัสดีครับ'));

    // รองรับ Enter key ใน input
    textInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') copyToClipboard(textInput.value);
    });
  </script>
</body>
</html>

การทำงาน

  • พิมพ์ข้อความในช่อง input แล้วกดปุ่ม "คัดลอก" หรือกด Enter
  • หรือกดปุ่ม "คัดลอกข้อความคงที่" เพื่อคัดลอกข้อความที่กำหนดไว้
  • แสดง Toast notification แจ้งสถานะ

Clipboard API vs execCommand

คุณสมบัติnavigator.clipboard.writeText()document.execCommand('copy')
สถานะมาตรฐานปัจจุบัน (Standard)Deprecated (ล้าสมัย)
Async/Promiseรองรับ (Async)Sync (บล็อก UI)
HTTPS Requiredต้องใช้ HTTPS หรือ localhostไม่จำเป็น
Permissionต้องได้รับอนุญาต (Permission API)ไม่ต้องการ
Browser SupportChrome 66+, Firefox 63+, Safari 13.1+, Edge 79+เก่าทั้งหมด (แต่จะถูกลบ)

Fallback สำหรับเบราว์เซอร์เก่า

async function copyToClipboard(text) {
  if (navigator.clipboard && window.isSecureContext) {
    return navigator.clipboard.writeText(text);
  }
  // Fallback สำหรับ HTTP หรือเบราว์เซอร์เก่า
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  try {
    document.execCommand('copy');
    return true;
  } finally {
    document.body.removeChild(textarea);
  }
}

ข้อควรระวัง

  • Clipboard API ต้องการ Secure Context (HTTPS หรือ localhost)
  • บางเบราว์เซอร์ต้องการ user gesture (คลิก/กดปุ่ม) ก่อนจึงจะอนุญาต
  • ควร handle error ด้วย try-catch เสมอ